如何制作多迹图作为可重用代码?
问题内容:
我以某种方式尝试使例如bar_graph的图的可重用代码为:
def bar(x,y,text,marker,orientation,name):
barchart=[go.Bar(x=x,y=y,text=text,marker=marker,orientation=orientation,name=name)]
........
以类似的方式如何为多个跟踪创建可重用的代码?
对于下面的代码,
fig = go.Figure()
# Add Traces
fig.add_trace(
go.Scatter(x=list(df.index),
y=list(df.High),
name="High",
line=dict(color="#33CFA5")))
fig.add_trace(
go.Scatter(x=list(df.index),
y=[df.High.mean()] * len(df.index),
name="High Average",
visible=False,
line=dict(color="#33CFA5", dash="dash")))
fig.add_trace(
go.Scatter(x=list(df.index),
y=list(df.Low),
name="Low",
line=dict(color="#F06A6A")))fig.update_layout(
updatemenus=[
go.layout.Updatemenu(
active=0,
buttons=list([
dict(label="None",
method="update",
args=[{"visible": [True, False, True, False]},
{"title": "Yahoo",
"annotations": []}]),
dict(label="High",
method="update",
args=[{"visible": [True, True, False, False]},
{"title": "Yahoo High",
"annotations": high_annotations}]),
dict(label="Low",
method="update",
args=[{"visible": [False, False, True, True]},
{"title": "Yahoo Low",
"annotations": low_annotations}]),
]),
)
])
# Set title
fig.update_layout(title_text="Yahoo")
fig.show()
在这里,跟踪将是任意的,即基于为每个跟踪传递的值的组合,那么如何使它成为可重用的代码?
.....
问题答案:
您可以轻松地遍历数据框的各列,并为它们的每一个创建跟踪,如下面的代码片段所示。
# crate traces
traces={}
for col in df.columns:
traces['trace_' + col]=go.Bar(x=df.index, name=col, y=df[col])
# convert data to form required by plotly
data=list(traces.values())
# build figure
fig=go.Figure(data)
fig.show()
与OP进行评论和聊天之后,编辑建议。
如果没有可重现的数据样本,很难提出理想的解决方案。但这是可重复使用的建议,其含义是:
(1): 关于源数据帧中的列数,它很灵活,并使用for循环根据请求添加跟踪,
(2): 计算每列的max()和min(),
(3): 它是一个函数结构,可以轻松应用于任何数据框。
我整理了一些示例数据,如下所示:
情节1:
代码1:
# Imports
import pandas as pd
import plotly.graph_objs as go
import matplotlib.pyplot as plt
import numpy as np
# data
humid = pd.Series(np.random.uniform(low=25, high=40, size=6).tolist())
windy = pd.Series(np.random.uniform(low=40, high=60, size=6).tolist())
df = pd.concat([humid,windy], axis = 1)
df.columns=['Humidity', 'windspeed']
df.index = ['Shanghai', 'Houston', 'Venice', 'Munich', 'Milan', 'Turin']
def plotMaxMin(df):
for col in df.columns:
#print(df[col].max())
df[col+'_max']=df[col].max()
df[col+'_min']=df[col].min()
# crate traces
traces={}
for col in df.columns:
traces['trace_' + col]=go.Scatter(x=df.index, name=col, y=df[col])
# convert data to form required by plotly
data=list(traces.values())
# build figure
fig=go.Figure(data)
fig.show()
plotMaxMin(df=df)
使用编辑的数据框测试可重用性:
情节2:
代码2:
df2=df.copy(deep=True)
df2['Temperature']=pd.Series(np.random.uniform(low=-5, high=40, size=6).tolist())
plotMaxMin(df2)
我们会错过的updatemnu()
。实际上,仅单击系列名称,该情节仍然具有很强的交互性。
使用go.layout.Updatemenu()测试
这需要更多的调整才能变得完美,但是主要功能似乎已经到位,因此我希望您能够添加一些东西以使其像数据集一样完美。
情节3:
代码3:
# Imports
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# data
humid = pd.Series(np.random.uniform(low=25, high=40, size=6).tolist())
windy = pd.Series(np.random.uniform(low=40, high=60, size=6).tolist())
df = pd.concat([humid,windy], axis = 1)
df.columns=['Humidity', 'windspeed']
df.index = ['Shanghai', 'Houston', 'Venice', 'Munich', 'Milan', 'Turin']
def plotMaxMin(df):
for col in df.columns:
#print(df[col].max())
df[col+'_max']=df[col].max()
df[col+'_min']=df[col].min()
# crate traces
traces={}
for col in df.columns:
traces['trace_' + col]=go.Scatter(x=df.index, name=col, y=df[col])
# convert data to form required by plotly
data=list(traces.values())
# build figure
fig=go.Figure(data)
# add dropdown functionality
fig.update_layout(
updatemenus=[
go.layout.Updatemenu(
active=0,
buttons=list([
dict(label="None",
method="update",
args=[{"visible": [True, False, True, False]},
{"title": "Yahoo",
"annotations": []}]),
dict(label="High",
method="update",
args=[{"visible": [True, True, False, False]},
{"title": "Yahoo High",
"annotations": high_annotations}]),
dict(label="Low",
method="update",
args=[{"visible": [False, False, True, True]},
{"title": "Yahoo Low",
"annotations": high_annotations}]),
]),
)
])
fig.show()
plotMaxMin(df=df)
编辑2:有关如何使用更多参数扩展功能以自定义图形的示例
情节4:
代码4:
# Imports
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# data
humid = pd.Series(np.random.uniform(low=25, high=40, size=6).tolist())
windy = pd.Series(np.random.uniform(low=40, high=60, size=6).tolist())
df = pd.concat([humid,windy], axis = 1)
df.columns=['Humidity', 'Windspeed']
df.index = ['Shanghai', 'Houston', 'Venice', 'Munich', 'Milan', 'Turin']
def plotMaxMin(df, colors):
"""Adds max and min for all df columns and plots the data using plotly
Arguments:
==========
df - pandas dataframe
colors - dictionary with single word to identify line category and assign color
Example call:
=============
plotMaxMin(df=df, colors={'wind':'#33CFA5', 'humidity':'#F06A6A'})
"""
# add max and min for each input column
for col in df.columns:
df[col+'_max']=df[col].max()
df[col+'_min']=df[col].min()
# sort df columns by name
df = df.reindex(sorted(df.columns), axis=1)
# crate traces
traces={}
for col in df.columns:
# format traces
if 'Humid' in col:
linecolor = colors['humidity']
if 'Wind' in col:
linecolor = colors['wind']
traces['trace_' + col]=go.Scatter(x=df.index, name=col, y=df[col], line=dict(color=linecolor))
# convert data to form required by plotly
data=list(traces.values())
# build figure
fig=go.Figure(data)
# uncomment bloew section to add dropdown functionality
#fig.update_layout(
#updatemenus=[
# go.layout.Updatemenu(
# active=0,
# buttons=list([
# dict(label="None",
# method="update",
# args=[{"visible": [True, False, True, False]},
# {"title": "Yahoo",
# "annotations": []}]),
# dict(label="High",
# method="update",
# args=[{"visible": [True, True, False, False]},
# {"title": "Yahoo High",
# "annotations": high_annotations}]),
# dict(label="Low",
# method="update",
# args=[{"visible": [False, False, True, True]},
# {"title": "Yahoo Low",
# "annotations": high_annotations}]),
# ]),
# )
#])
fig.show()
plotMaxMin(df=df, colors={'wind':'#33CFA5', 'humidity':'#F06A6A'})