Python 如何用plotly绘制金字塔人口图?

Python 如何用plotly绘制金字塔人口图?,python,plotly,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'

我想用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')
输出:

使用负数将条放置在左侧。调整轴刻度标签

导入plotly.graph\u objs as go
将plotly.offline作为pyo导入
作为pd进口熊猫
从导入数据帧
df=pd.DataFrame({
‘年龄’:[‘11’、‘19’、‘22’、‘30’、‘24’、‘27’、‘15’],
'组':['A','B','C','C','B','C','B'],
‘性别’:[‘男性’、‘女性’、‘男性’、‘女性’、‘女性’、‘男性’、‘男性’],
“计数”:[3,5,6,1,4,5,2]
})
#当然是一样的,现在我是按性别分开的
女性=df['count'][df['gender']=='Female']
男性=df['count'][df['gender']=='Male']
y=df[‘年龄’]
xtick=list([6,-4,-2,0,2,4,6])
layout=go.layout(yaxis=go.layout.yaxis(title='Age'),
xaxis=go.layout.xaxis(
范围=[-df['count'].max(),df['count'].max(),
滴答声=滴答声,
ticktext=[str(abs(x))表示x在xtick中的位置],
title='Number'),
barmode='overlay',
bargap=0.1)
数据=[go.Bar(y=y,
x=男性垃圾箱,
方向='h',
name='Men',
hoverinfo='x',
marker=dict(颜色为蓝色)
),
go.Bar(y=y,
x=-女性垃圾箱,
方向='h',
name='Women',
text=1*women_bins.astype('int'),
hoverinfo='text',
marker=dict(color='seagreen')
)]
pyo.iplot(dict(数据=数据,布局=布局))

我不清楚你的额外要求。@斯诺请在发表文章时只问一个问题。图表不正确,男性和女性的结果完全相同,而在数据表中他们不一样。对不起,我只是根据你给我的示例绘制了图。请参见
男性垃圾箱
女性垃圾箱