[英]Plot plotly boxplots in subplots using for loop
我有一个 Dataframe (df)。 我想 plot 每列的箱线图,并且这些显示为子图。 但是,以下代码给出了错误。
from plotly.subplots import make_subplots
import plotly.express as px
import pandas as pd
fig = make_subplots(rows = 5, cols = 2)
for i, column in enumerate(df.select_dtypes(include = np.number).columns.tolist()):
fig.add_trace(px.box(df, y = [column]), row = i%5, col = i//5)
fig.update_layout(width = 800, height = 800)
fig.show()
错误:“----> 5 fig.add_trace(px.box(df, y = [column]), row = i%5, col =i//5)”
在我结束时,您的代码片段触发:
'data' 属性是跟踪实例的元组,可以指定为:
- 跟踪实例的列表或元组(例如 [Scatter(...), Bar(...)])
- 单个跟踪实例
这是因为fig.add_trace
旨在将trace objects
作为输入,例如go.Box
,而不是您在此处使用的px.box
返回的figure objects
。 因此,您可以使用类似的东西来代替它:
# plotly setup
plot_rows=6
plot_cols=6
fig = make_subplots(rows=plot_rows, cols=plot_cols)
# add traces
x = 0
for i in range(1, plot_rows + 1):
for j in range(1, plot_cols + 1):
#print(str(i)+ ', ' + str(j))
fig.add_trace(go.Box(y=df[df.columns[x]].values,
name = df.columns[x],
),
row=i,
col=j)
x=x+1
并得到:
## imports
from plotly.subplots import make_subplots
import plotly.graph_objs as go
import pandas as pd
import numpy as np
# data
np.random.seed(123)
frame_rows = 10
n_plots = 36
frame_columns = ['B_'+str(e) for e in list(range(n_plots+1))]
df = pd.DataFrame(np.random.uniform(-10,10,size=(frame_rows, len(frame_columns))),
index=pd.date_range('1/1/2020', periods=frame_rows),
columns=frame_columns)
df=df.cumsum()+100
df.iloc[0]=100
# plotly setup
plot_rows=6
plot_cols=6
fig = make_subplots(rows=plot_rows, cols=plot_cols)
# add traces
x = 0
for i in range(1, plot_rows + 1):
for j in range(1, plot_cols + 1):
#print(str(i)+ ', ' + str(j))
fig.add_trace(go.Box(y=df[df.columns[x]].values,
name = df.columns[x],
),
row=i,
col=j)
x=x+1
# Format and show fig
fig.update_layout(height=1200, width=1200)
fig.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.