如何使用my dataframe结构绘制未堆叠的条形图?

2024-04-26 05:41:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试绘制一个未加标记的条形图,用于按年份区分的成对产品。即,2020年和2021年之间,产品1的X有什么不同

我有一个具有挑战性的dataframe结构,因此不确定如何使其适合Plotly的无堆栈条形图框架?我希望有人能给我带路。谢谢

数据帧:

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

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

enter image description here


2条回答
  1. 使用熊猫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")

enter image description here

您可以尝试:

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

enter image description here

相关问题 更多 >

    热门问题