英文:
How to plot bar graph with two column values parallely in a single figure using plotly?
问题
我有一个pandas数据框,显示在每个购物中心,男性花了多少钱,女性花了多少钱。就像这样 -
ShoppingMall MaleSpends FemaleSpends
0 XX 5600.20 4500.70
1 YY 9000.00 100000.00
2 zz 7809.45 5600.89
在一个图表中,我需要绘制男性支出和女性支出。
我可以在Plotly中分别绘制这些图表 -
import plotly.express as px
fig1=px.bar(data,x='ShoppingMall',y='MaleSpends',barmode='group')
fig2=px.bar(data,x='ShoppingMall',y='FemaleSpends',barmode='group')
但我需要在一个图中绘制男性和女性花费的金额。
一个截图如下所示:
英文:
I have a pandas dataframe which shows in each shopping mall, how much the males spend money and how much the females spend money. Its like this -
ShoppingMall MaleSpends FemaleSpends
0 XX 5600.20 4500.70
1 YY 9000.00 100000.00
2 zz 7809.45 5600.89
In one graph I have to plot the malespends and femalespends.
I can plot the graphs separately in plotly -
import plotly.express as px
fig1=px.bar(data,x='ShoppingMall',y='MaleSpends',barmode='group')
fig2=px.bar(data,x='ShoppingMall',y='FemaleSpends',barmode='group')
But I need to plot the money spent by males and females in one figure.
A screenshot is shown .
答案1
得分: 0
import plotly.graph_objects as go
# 创建一个具有两个图迹的图形
fig = go.Figure()
# 用于MaleSpends的第一个图迹
fig.add_trace(
go.Bar(
x=data['ShoppingMall'],
y=data['MaleSpends'],
name='男性支出'
)
)
# 用于FemaleSpends的第二个图迹
fig.add_trace(
go.Bar(
x=data['ShoppingMall'],
y=data['FemaleSpends'],
name='女性支出'
)
)
# 更新布局以显示图例并堆叠条形图
fig.update_layout(
barmode='group',
title_text='购物中心的性别支出',
xaxis_title='购物中心',
yaxis_title='支出',
)
# 显示图表
fig.show()
英文:
import plotly.graph_objects as go
# Create a figure with two traces
fig = go.Figure()
# First trace for MaleSpends
fig.add_trace(
go.Bar(
x=data['ShoppingMall'],
y=data['MaleSpends'],
name='Male Spends'
)
)
# Second trace for FemaleSpends
fig.add_trace(
go.Bar(
x=data['ShoppingMall'],
y=data['FemaleSpends'],
name='Female Spends'
)
)
# Update layout to show the legend and to stack the bars
fig.update_layout(
barmode='group',
title_text='Spending by Gender in Shopping Malls',
xaxis_title='Shopping Mall',
yaxis_title='Spends',
)
# Show the plot
fig.show()
This will create a grouped bar plot where each mall has two bars side-by-side - one for MaleSpends
and another for FemaleSpends
. If you want a stacked bar plot where each mall has a single bar, with MaleSpends
and FemaleSpends
stacked on top of each other, just change barmode
to 'stack'
in the update_layout
call.
答案2
得分: 0
在其最简单形式下,使用plotly的express函数创建代码,可以使用以下一行代码创建图形。
px.bar(df, x='ShoppingMall', y=['MaleSpends', 'FemaleSpends'], barmode='group')
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论