0

How to plot this dataframe below with its value AND percentage on the chart?

    Activity Month  Total Monthly Actual Hours  Total Monthly Work Hours
0   Apr-19          35381.25                    42592
1   May-19          31722.50                    44528
2   Jun-19          27708.50                    38720
3   Jul-19          34283.50                    44528
4   Aug-19          32225.60                    42592

For now I only can plot it normally using this code:

display(df.reset_index())

df.plot(kind='bar').tick_params(rotation = 0)
plt.ylabel('Work Hours')
plt.xlabel('Month')

enter image description here

I wanted to plot this chart to be like this:

enter image description here

Firdhaus Saleh
  • 189
  • 2
  • 13
  • Possible duplicate of [How to display the value of the bar on each bar with pyplot.barh()?](https://stackoverflow.com/questions/30228069/how-to-display-the-value-of-the-bar-on-each-bar-with-pyplot-barh) – Tserenjamts Nov 11 '19 at 03:38

1 Answers1

2

One way to do the percentages on the fly:

df = pd.DataFrame(...)

ax = df.plot(kind='bar')

ax.tick_params(rotation = 0)

for date, (p, q) in enumerate(zip(df["Total_Monthly_Actual_Hours"],df["Total_Monthly_Work_Hours"])):
    ax.annotate(f"{p}\n({(p/q)*100:.0f}%)", (date-0.25, p*1.02), size=7)
    ax.annotate(f"{q}\n({(q/q)*100:.0f}%)", (date, q*1.02), size=7)

plt.ylabel('Work Hours')
plt.xlabel('Month')

plt.show()

enter image description here

Henry Yik
  • 22,275
  • 4
  • 18
  • 40
  • Idk why I'm receiving this error ------> TypeError: unsupported operand type(s) for -: 'str' and 'float' – Firdhaus Saleh Nov 11 '19 at 04:16
  • You have to tell which line you got this error. In the above `set_index` is called on the plot instead of the actual `df`, so make sure your index and columns are not string. – Henry Yik Nov 11 '19 at 04:18
  • This 2 lines below, maybe regarding on convertion from Apr-19 to coordinate. ------------------------------------------------------------------------ ax.annotate(f"{p}\n({(p/q)*100:.0f}%)", (date-0.25, p*1.02), size=7) ax.annotate(f"{q}\n({(q/q)*100:.0f}%)", (date, q*1.02), size=7) – Firdhaus Saleh Nov 11 '19 at 04:21
  • Is your index set to date in your original df? – Henry Yik Nov 11 '19 at 04:23