python - 使用 for 循环在子图中绘制箱形图

标签 python plotly boxplot

我有一个数据框(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

并得到:

enter image description here

完整代码:

## 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/

相关文章:

python - 获取所有可用的存储桶并打印但仅使用存储桶名称

python - Flask-Admin:更改 inline_models 的排序顺序?

python - 类似于plotly中seaborn的hue函数?

python - 斧头反转时无法设置范围-plotly

python - 基于另一个列过滤器在列中进行空/重复检查

python - 如何检测 Blobstore 条目是否是图像,以便 get_serving_url 可以工作?

python - 在 plotly 中使用 x 范围 slider 进行 Y 轴自动缩放

python - Seaborn 和 Pandas,分组箱线图

r - 将 fiddle 图与闪避的箱形图对齐

r - 将箱线图的 geom_segment 和中位数添加到图例中