0

I have this pandas dataframe:

   production  consumption
year        
2013    0.426669    0.573331
2014    0.436364    0.563636
2015    0.419941    0.580059
2016    0.448378    0.551622
2017    0.442212    0.557788
2018    0.422724    0.577276
2019    0.445296    0.554704

and I plot a stacked bar chart using df.plot.bar(stacked=True) function

graph

Productions and consumptions are in %

Is it possible to add percentages into bars?

Code Different
  • 90,614
  • 16
  • 144
  • 163
mikou
  • 3
  • 2

1 Answers1

3

It's harder than it should be but it's doable:

ax = df.plot.bar(stacked=True)
labels = [f'{i:.0%}' for i in df.to_numpy().flatten(order='F')]

for i, patch in enumerate(ax.patches):
    x, y = patch.get_xy()
    x += patch.get_width() / 2
    y += patch.get_height() / 2
    ax.annotate(labels[i], (x, y), ha='center', va='center', c='white')

Result:

enter image description here

Code Different
  • 90,614
  • 16
  • 144
  • 163