如何制作多迹图作为可重用代码? [英] How to make a multiple trace plot as a reusable code?
问题描述
我以某种方式尝试将例如bar_graph的图的可重用代码制作为:
I somehow tried to make the reusable code of plots for eg a bar_graph as:
def bar(x,y,text,marker,orientation,name):
barchart=[go.Bar(x=x,y=y,text=text,marker=marker,orientation=orientation,name=name)]
........
以类似的方式如何为多个跟踪创建可重用的代码?
In a similar way how can I make a reusable code for multiple traces ?
对于以下代码,
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()
在这里,跟踪将是任意的,即基于为每个跟踪传递的值的组合,那么如何使它成为可重用的代码?
here, the traces would be of any,i.e., based on combination of values passed for each trace, so how can I make it as a reusable code?
.....
推荐答案
您可以轻松地遍历数据框的各个列,并为每个列创建跟踪,如下面的代码片段所示.
You can easily loop through the columns of your dataframe and create a trace for each of them like in the snippet below.
# 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对话后编辑的建议.
没有可重复的数据样本,很难提出理想的解决方案.但这是可重复使用的建议,其含义是:
Edited suggestion after conversations with OP in comments and chat.
Without a reproducible data sample, it's a bit hard to suggest a perfect solution. But here's a suggestion that is reusable in the sense that:
(1):关于源数据帧中的列数,它很灵活,并使用for循环根据请求添加跟踪,
(1): it's flexible with regards to the number of columns in your source dataframe and uses a for loop to add traces as requested,
(2):,它为每一列计算max()和min(),
(2): it calculates max() and min() for each column,
(3)::它是一种函数结构,可以轻松应用于任何数据框.
(3): it is structured as a function and can easiliy be applied to any dataframe.
我整理了一些示例数据,如下所示:
I've put together some sample data that looks like this:
情节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()
.照原样,只需单击系列名称,情节仍然具有很强的交互性.
We're sill missing the updatemnu()
. As it is, the plot still is pretty interactive by only clicking the names of the series.
这需要更多的调整才能变得完美,但是主要功能似乎已经到位,所以我希望您能够添加一些东西来使它像您的数据集一样完美.
This will take some more tweaking to make perfect, but the main functioanlities seem to be in place, so I hope you'll be able to add a few things to get it exaclty like you want with your dataset.
图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)
有关如何使用更多参数扩展功能以自定义图形的示例
图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'})
这篇关于如何制作多迹图作为可重用代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!