简体   繁体   English

Plotly单杠比较

[英]Plotly horizontal bar comparizon

The chart attached is from R plotly package. Does this exist or can be done in python using the plotly package?所附图表来自 R plotly package。这是否存在或可以使用 plotly package 在 python 中完成? 在此处输入图像描述

You can create diverging stacked bars in plotly-python by plotting the bars for male and female populations as separate traces, making the population values negative for the men, and then using the original values in the customdata so the populations for men display positive values.您可以在 plotly-python 中创建发散堆积条,方法是将男性和女性人口的条形图绘制为单独的轨迹,使男性的人口值为负,然后使用自定义数据中的原始值,以便男性的人口显示正值。

I followed the method outlined by @empet in his answer here , and modified the categories and hovertemplate to fit your example.我遵循了@empet 在此处的回答中概述的方法,并修改了类别和悬停模板以适合您的示例。

import numpy as np
import pandas as pd
import plotly.graph_objects as go

d = {'Age': ['0-19','20-29','30-39','40-49','50-59','60-Inf'],
     'Male': [1000,2000,4200,5000,3500,1000],
     'Female': [1000,2500,4000,4800,2000,1000],
}
df = pd.DataFrame(d)

fig = go.Figure()
fig.add_trace(go.Bar(x=-df['Male'].values,
                        y=df['Age'],
                        orientation='h',
                        name='Male',
                        customdata=df['Male'],
                        hovertemplate = "Age: %{y}<br>Pop:%{customdata}<br>Gender:Male<extra></extra>"))
fig.add_trace(go.Bar(x= df['Female'],
                        y =df['Age'],
                        orientation='h',
                        name='Female',
                        hovertemplate="Age: %{y}<br>Pop:%{x}<br>Gender:Female<extra></extra>"))    

fig.update_layout(barmode='relative', 
                  height=400, 
                  width=700, 
                  yaxis_autorange='reversed',
                  bargap=0.01,
                  legend_orientation ='h',
                  legend_x=-0.05, legend_y=1.1
                 )
fig.show()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM