我有一个数据框(df)。我想绘制每列的箱线图,并将它们显示为子图。但是,下面的代码会出错。
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)”
最佳答案
在我这边,您的代码片段会触发:
The 'data' property is a tuple of trace instances that may be specified as:
- A list or tuple of trace instances (e.g. [Scatter(...), Bar(...)])
- A single trace instance
这是因为 fig.add_trace
被设计为将 trace 对象
作为输入,例如 go.Box
,而不是您在此处使用的 px.box
返回的 figure 对象
。因此,您可以使用类似以下内容来代替:
# 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()
关于python - 使用 for 循环在子图中绘制箱形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66846435/