首页 > 解决方案 > 如何用 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')

输出: 图表输出

标签: pythonplotly

解决方案


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

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))

在此处输入图像描述


推荐阅读