-1

The chart attached is from R plotly package. Does this exist or can be done in python using the plotly package? enter image description here

Derek O
  • 16,770
  • 4
  • 24
  • 43
Seph77
  • 75
  • 8

1 Answers1

0

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.

I followed the method outlined by @empet in his answer here, and modified the categories and hovertemplate to fit your example.

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

enter image description here

Derek O
  • 16,770
  • 4
  • 24
  • 43
  • one small question is there a way to remove the X axis? overall super great. I appreciate your help – Seph77 Mar 02 '22 at 14:35
  • @Seph77 no problem - happy to help! you can hide the xaxis by using `fig.update_xaxes(visible=False)` – Derek O Mar 02 '22 at 17:49
  • Sorry One more question when I use the text attribute is there a way to hide the negative so for instance doesn't show -100 but 100 on the left side of the bar? – Seph77 Mar 02 '22 at 19:44
  • @Seph77 you mean that when you hover over the bars to the left of 0, you want it the hovertemplate to show positive values instead of negative values? – Derek O Mar 02 '22 at 21:15