4

With the code below, one can plot this chart:

what I have so far

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([[55., 56.], [38., 35.], [7., 9.]], index=['Yes', 'No', "Don't know"], columns=['males', 'females'])
plt.style.use('ggplot')
df.T.plot(kind='barh', stacked=True, colormap='Blues', legend=False)
plt.xticks(range(0, 101, 10), [str(x) + "%" for x in range(0, 101, 10)])
plt.xlim([0, 100])
plt.savefig('chart.pdf', bbox_inches='tight')

I would like to have the different bars labeled with the corresponding numbers. Because the bars are stacked, the labels should be printed in the bars:

desired result

Is there an option in the pandas or matplotlib plot functions for this?

Fabian Heller
  • 430
  • 7
  • 10
  • perhaps this question will help http://stackoverflow.com/questions/19917587/matplotlib-advanced-bar-plot/19919397#19919397 – Paul H Dec 08 '14 at 19:47
  • This might be quite tricky, as `pandas.Series.plot` only returns the `axes` object but not the `patches`. So it is difficult to compute the positions for the text. [Here](http://stackoverflow.com/questions/21397549) is a (similar) pure matplotlib solution. – hitzg Dec 09 '14 at 09:42
  • This [answer](https://stackoverflow.com/questions/49601890/display-label-stacked-barh-with-values-from-dataframe/49708845#49708845) may help you. You'll have to tweak the position of labels to get them in the middle. – Chris Apr 07 '18 at 15:26

0 Answers0