[英]How do I plot a unstacked bar graph with a my dataframe structure?
I am trying to plot an unstacked bar chart for pairs of products differentiated by the year.我正在尝试为按年份区分的产品对绘制未堆叠的条形图。 Ie what is the difference in X for product 1 between 2020 and 2021?
即产品 1 在 2020 年和 2021 年之间的 X 有什么不同?
I have a challenging dataframe structure and thus not sure how I can shape it to fit Plotly's unstacked bar chart framework?我有一个具有挑战性的数据框结构,因此不确定如何调整它以适合 Plotly 的非堆叠条形图框架? I hope someone can guide.Thanks
希望有人指导谢谢
dataframe:数据框:
Date | Shoes__sale_x | Category_x | Shoes__sale_y | Category_y
Jan | $20 | 2020 | $25 | 2021
Feb | $24 | 2020 | $75 | 2021
I want the bar chart to look like this where the legend would display the Category (ie 2020 or 2021).我希望条形图看起来像这样,其中图例将显示类别(即 2020 或 2021)。 How would I best do this?
我怎么做最好?
You can try:你可以试试:
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
wide_to_long()
wide_to_long()
构建您的数据框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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.