【问题标题】:ValueError: Wrong number of items passed 3, placement implies 1ValueError:错误的项目数通过 3,位置暗示 1
【发布时间】:2021-11-26 07:46:40
【问题描述】:

我想绘制 plotly express 分组条形图以显示每个十年中的出生人数,仅like this graph

pivot_dayofweek=final.pivot_table(values='births',index='dayofweek',columns='decade',aggfunc='mean')    



pivot_dayofweek=pivot_dayofweek.loc[['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday']]
pivot_dayofweek

pivot_dayofweek dataframe

px.bar(pivot_dayofweek,x=pivot_dayofweek.index,y=pivot_dayofweek.values,barmode='group')

但是当我运行上面的代码时,它给了我一个错误Click to show the error

【问题讨论】:

    标签: python pandas plotly data-visualization plotly-express


    【解决方案1】:
    • 有模拟数据集和数据透视表
    • 最简单的方法是重构数据透视图,为 plotly 做好准备
      1. stack() decade 列到索引中
      2. reset_index() 制作索引列
      3. decade 设为字符串以防止将其视为连续
    import pandas as pd
    import numpy as np
    import plotly.express as px
    
    df = pd.DataFrame({"date": pd.date_range("1-jan-1960", "31-dec-1989", freq="D")}).pipe(
        lambda d: d.assign(
            births=np.random.uniform(1, 5, len(d)),
            dayofweek=d["date"].dt.strftime("%A"),
            decade=d["date"].dt.year - d["date"].dt.year % 10,
        )
    )
    
    dfp = df.pivot_table(
        values="births", index="dayofweek", columns="decade", aggfunc="sum"
    )
    
    px.bar(
        dfp.stack().reset_index().assign(decade=lambda d: d["decade"].astype(str)),
        color="decade",
        x="dayofweek",
        y=0,
        barmode="group",
    ).update_layout(title="No of birth in day in every decade", yaxis={"title":"Births"})
    

    【讨论】:

      猜你喜欢
      • 2019-09-23
      • 2019-02-25
      • 2016-02-14
      • 2020-09-17
      • 2021-12-12
      • 2021-04-08
      • 2020-01-30
      • 2021-07-05
      • 2021-07-13
      相关资源
      最近更新 更多