plotly笔记-- 图形设置
文章目录
- plotly笔记-- 图形设置
-
- 准备工作
- 1、多图标
- 2、双坐标轴
- 3、多子图
这篇文章将简单描述plotly图形设置相关的内容,文中使用到的数据是从天池下载的经典泰坦尼克训练数据集,需要此数据的小朋友们可以前往天池下载,我也会将文中使用到的数据和源代码放在Github上以便下载: Github
准备工作
这次笔记所用数据与上篇文章相同,所以前期准备工作也是相同的
import pandas as pd
import numpy as np
import os
# 查看当前路径
os.getcwd()
# 更改当前工作目录
os.chdir("F:/天池数据集/泰坦尼克/")
# 将目录里的内容输出为列表
os.listdir()
# 读入数据
titain_data = pd.read_csv("titanic_train.csv")
# 对数据情况大致了解一下
titain_data.head()
titain_data.info()
titain_data.describe()
# 对Age项统计缺失值
titain_data["Age"].isnull().sum()
# 对Age的空值进行前向替换
titain_data["Age"].fillna(method="ffill", inplace=True)
titain_data["Age"].isnull().sum()
titain_data["Age"].describe()
# 对数据中年龄进行分段统计
w = [0, 15, 30, 45, 60, 100]
titain_data["Age_bin"] = pd.cut(
titain_data["Age"],
bins=w,
labels=['0-15岁', '15-30岁', '30-45岁', '45-60岁', '60岁以上'],
right=False)
Age_x = titain_data["Age_bin"].value_counts(sort=False)
# titain_data.head()
Age_x
# x = list(Age_x.index)
# y = Age_x.values
1、多图标
不同图形的组合展示
例如:柱状图+线形图
import plotly.graph_objects as go
# 多图标
# 例如:柱状图+线形图
mean_value = np.mean(Age_x.values.tolist())
# 将mean_value沿X轴复制
y = np.tile(mean_value,5)
y
trace_bar = go.Bar(x=Age_x.index.tolist(),
y=Age_x.values.tolist(),
marker=dict(
color=["blue", "red", "green", "indianred", "darkgrey"],
opacity=0.4),
name="Bar")
trace_average = go.Scatter(x=Age_x.index.tolist(),
y=y,
mode="lines",
name="平均值")
data = [trace_bar, trace_average]
layout = go.Layout(title="不同年龄段人数对比", xaxis=dict(title="年龄段"))
fig = go.Figure(data=data, layout=layout)
fig.show()
2、双坐标轴
N = 50
random_x = np.linspace(0, 1, N)
random_y0 = np.random.randn(N)
random_y1 = np.random.randn(N) * 150
#Create traces
trace0 = go.Scatter(x=random_x, y=random_y0, mode='lines', name='小数值展示')
trace1 = go.Scatter(x=random_x,
y=random_y1,
mode='lines+markers',
name='大数值展示',
yaxis="y2")
data1 = [trace0, trace1]
# go.Layout可以创建图层对象,实现双坐标
layout = go.Layout(title="双坐标示例图",
yaxis=dict(title="小数值"),
yaxis2=dict(title="大数值", overlaying='y', side="right"),
legend=dict(x=0, y=1, font=dict(size=12, color="black")))
fig = go.Figure(data=data1, layout=layout)
fig.show()
3、多子图
# 多子图绘制 如:将上面用到的图形一起绘制
# 导入subplots(类似matplotlib)
from plotly import subplots
# 设定布局,以便进行绘图,这儿是两行一列
fig = subplots.make_subplots(rows=2,cols=1)
#This is the format of your plot grid:
#[ (1,1) x1,y1 ]
#[ (2,1) x2,y2 ]
fig.append_trace(trace_bar,1,1)
fig.append_trace(trace0,2,1)
# 设定每个子图的占位情况
fig.layout.yaxis1.domain = [0.35,1.0]
fig.layout.yaxis2.domain = [0,0.3]
# 设定整个fig的大小
fig.layout.width = 800
fig.layout.height = 600
fig.show()
更多关于Subplots相关内容可以参考官方文档:Subplots