【问题标题】:How do I plot a unstacked bar graph with a my dataframe structure?如何使用我的数据框结构绘制未堆叠的条形图?
【发布时间】:2021-12-02 13:05:24
【问题描述】:

我正在尝试为按年份区分的成对产品绘制一个未堆叠的条形图。 IE。 2020 年和 2021 年产品 1 的 X 有什么区别?

我有一个具有挑战性的数据框结构,因此不确定如何调整它以适应 Plotly 的非堆叠条形图框架?希望有人指导。谢谢

数据框:

Date | Shoes__sale_x | Category_x | Shoes__sale_y | Category_y
Jan  |  $20            | 2020       |  $25           | 2021
Feb  |  $24            | 2020       |  $75           | 2021

我希望条形图看起来像这样,图例将显示类别(即 2020 或 2021)。我该怎么做才最好?

【问题讨论】:

  • 如果你使用plotly请去掉seaborn标签

标签: python pandas plotly


【解决方案1】:

你可以试试:

import plotly.express as px
df_sub = df.melt(id_vars=['Date'], value_vars=['Shoes__sale_x', 'Shoes__sale_y'], var_name='sales')
df_sub['value'] = df_sub['value'].str[1:].astype(int)
fig = px.bar(df_sub, x="Date", y="value", color='sales', barmode='group', height=600)
fig.update_layout(yaxis_title='Price', title='Chart Title')
fig.show()

Plot

【讨论】:

    【解决方案2】:
    1. pandas wide_to_long() 构建您的数据框
    2. 使用 plotly express 从结构化数据生成
    import io
    import pandas as pd
    import plotly.express as px
    
    df = pd.read_csv(io.StringIO("""Date | Shoes__sale_x | Category_x | Shoes__sale_y | Category_y
    Jan  |  $20            | 2020       |  $25           | 2021
    Feb  |  $24            | 2020       |  $75           | 2021"""), sep="\s+\|\s+", engine="python")
    
    df2 = pd.wide_to_long(df, stubnames=["Shoes__sale_", "Category_"], i="Date", j="Sale", suffix=r'\w+').reset_index()
    df2["Shoes__sale_"] = df2["Shoes__sale_"].str.strip("$").astype(float)
    
    px.bar(df2, x="Date", y="Shoes__sale_", color="Sale", hover_data=["Category_"], barmode="group")
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-19
    • 1970-01-01
    • 2020-02-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多