【问题标题】:Making multiple plots using two loops使用两个循环制作多个绘图
【发布时间】:2021-04-02 13:15:20
【问题描述】:

我有这个数据:https://www.kaggle.com/uciml/mushroom-classification。 我已按目标列值拆分数据框,并尝试并排绘制数据框图以分析差异。我为每个数据帧使用了两个 for 循环。这是我的代码:

edible = df[df['class']=='e']
poisonous = df[df['class']=='p']

for i in edible:
    fig = px.bar(x=df[i].value_counts().index, y=df[i].value_counts(), text= 
(df[i].value_counts()/len(df[i])*100),title=str(i)+' Edible Mushroom Distribution')
    fig.show()
    
for j in poisonous:
    fig = px.bar(x=df[j].value_counts().index, y=df[j].value_counts(), text=(df[j].value_counts()/len(df[i])*100),title=str(i)+' Poisonous Mushroom Distribution')
fig.show()  

代码成功创建了所有的情节,但有两个问题:

  1. 显示所有图需要两个时间
  2. 我需要将列并排进行分析,我不知道如何实现。

谁能帮帮我。 谢谢

【问题讨论】:

标签: python pandas plotly


【解决方案1】:

plotly 中的子图是使用“make_subplots”创建的。第一步是确定复数图的骨架(矩阵的大小),然后指定图的类型。之后,您可以使用自己的代码。也可以参考官方reference添加标题和装饰。

import plotly.graph_objects as go
from plotly.subplots import make_subplots

edible = df[df['class']=='e']
poisonous = df[df['class']=='p']

fig = make_subplots(rows=len(edible.columns), # len(edible.columns)
                    cols=2,
                    column_widths=[0.5, 0.5],
                    specs=[[{'type':'bar'},{'type':'bar'}] for i in range(len(edible.columns))])

for i,col in enumerate(edible):
    fig.add_trace(
        go.Bar(x=edible[col].value_counts().index, y=edible[col].value_counts(), ), row=i+1, col=1)
    fig.add_trace(
        go.Bar(x=poisonous[col].value_counts().index, y=poisonous[col].value_counts(), ), row=i+1, col=2)

fig.update_layout(height=2000)
fig.show()

【讨论】:

  • 实际上我确实使用了 make.subplot 但我使用了两个循环并且不知道如何为每个循环分配行和列。非常感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 2021-05-25
  • 1970-01-01
  • 1970-01-01
  • 2018-03-16
  • 2021-02-20
  • 2022-01-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多