python - 如何用 plotly 绘制金字塔人口图?
问题描述
我想用 plotly 绘制人口金字塔图。我想要我的输出似乎完全错误。经过大量研究,我找不到可行的解决方案。非常感谢您的帮助。
我的代码:
import plotly.graph_objs as go
import plotly.offline as pyo
import pandas as pd
from pandas import DataFrame
df = pd.DataFrame({
'age': ['11', '19', '22', '30', '24', '27', '15'],
'group': ['A', 'B', 'C', 'C', 'B', 'C', 'B'],
'gender': ['Male','Female','Male','Female','Female','Male','Male'],
'count':[3,5,6,1,4,5,2]
})
women_bins = df['count']
men_bins = df['count']
y = df['age']
layout = go.Layout(yaxis=go.layout.YAxis(title='Age'),
xaxis=go.layout.XAxis(
range=[-df['count'].max(), df['count'].max()],
title='Number'),
barmode='overlay',
bargap=0.1)
data = [go.Bar(y=y,
x=men_bins,
orientation='h',
name='Men',
hoverinfo='x',
marker=dict(color='powderblue')
),
go.Bar(y=y,
x=women_bins,
orientation='h',
name='Women',
text=1 * women_bins.astype('int'),
hoverinfo='text',
marker=dict(color='seagreen')
)]
pyo.iplot(dict(data=data, layout=layout), filename='EXAMPLES/bar_pyramid')
解决方案
使用负数将条形放置在左侧。调整轴刻度标签。
import plotly.graph_objs as go
import plotly.offline as pyo
import pandas as pd
from pandas import DataFrame
df = pd.DataFrame({
'age': ['11', '19', '22', '30', '24', '27', '15'],
'group': ['A', 'B', 'C', 'C', 'B', 'C', 'B'],
'gender': ['Male','Female','Male','Female','Female','Male','Male'],
'count':[3,5,6,1,4,5,2]
})
# Of course it was the same, now I separated by gender
women_bins = df['count'][df['gender'] == 'Female']
men_bins = df['count'][df['gender'] == 'Male']
y = df['age']
xtick =list([6,-4, -2, 0, 2, 4, 6])
layout = go.Layout(yaxis=go.layout.YAxis(title='Age'),
xaxis=go.layout.XAxis(
range=[-df['count'].max(), df['count'].max()],
tickvals=xtick,
ticktext=[str(abs(x)) for x in xtick],
title='Number'),
barmode='overlay',
bargap=0.1)
data = [go.Bar(y=y,
x=men_bins,
orientation='h',
name='Men',
hoverinfo='x',
marker=dict(color='powderblue')
),
go.Bar(y=y,
x=-women_bins,
orientation='h',
name='Women',
text=1 * women_bins.astype('int'),
hoverinfo='text',
marker=dict(color='seagreen')
)]
pyo.iplot(dict(data=data, layout=layout))
推荐阅读
- flutter - 新的颤振更新强制零安全?
- python - 在 C++ 中嵌入/包含 Python.h [完整指南] (Python 3.9) (Windows) (Qt 5.15)
- reactjs - 在 wpengine 上运行 ReactJS 构建,其中放置了 wordpress 代码
- php - PHP上传视频,进入数据库而不是文件夹
- excel - 插入三维数据的替代方法
- java - LayerList xml如何在android中中断?
- visual-studio - 如何在 msbuild 宏中获取 nuget 存储库路径?
- jestjs - 清除测试之间的笑话不工作
- python - 使用 Selenium 实现边缘自动化 - 不断需要凭据
- ios - 带有动态页脚的 UIScrollView