私はどういうわけか、たとえば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()
再現可能なデータサンプルがなければ、完璧な解決策を提案するのは少し難しいです。しかし、次のような意味で再利用可能な提案があります。
(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()
。それがそうであるように、プロットはシリーズの名前をクリックするだけでまだかなりインタラクティブです。
これを完璧にするにはさらに調整が必要ですが、主な機能は整っているように見えるので、データセットで必要なように正確にするためにいくつか追加できることを願っています。
プロット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'})
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加