0

I want to put my text vertically inside the bar graph. I tried, but couldn't get hold of it.

import pandas as pd
import matplotlib.pyplot as plt

dataF = pd.DataFrame({
    'date':['12 Jul, 15','30 Aug, 17','23 Dec,19','12 Mar,21'],
    'revenue':[34,25,30,38],
    'status':['PAID','NOT PAID','PAID','NOT PAID']
})
print(dataF)

         date  revenue    status
0  12 Jul, 15       34      PAID
1  30 Aug, 17       25  NOT PAID
2   23 Dec,19       30      PAID
3   12 Mar,21       38  NOT PAID

plt.close('all')
plt.rcParams['figure.figsize']=(10,6)
fig,ax = plt.subplots()
rects = ax.bar(dataF['date'], dataF['revenue'],
    width=0.2, color = 'orange')
def autolabel(rects):
    for rect in rects:
        h = rect.get_height()
        ax.text(rect.get_x()+rect.get_width()/2., 1.02*h,
                str(''),  ha='center', va='bottom')
autolabel(rects)
plt

Now, I want the status to appear inside the bars vertically, just as I did manually below.

enter image description here

1 Answer 1

3

How about joining the string with newlines like so

'\n'.join(status)

In total something like

fig, ax = plt.subplots()
rects = ax.bar('date', 'revenue', width=0.2, color='orange', data=dataF)
for status, r in zip(dataF['status'], rects):
    ax.text(r.get_x() + r.get_width()/2., 0.95 * r.get_height(), 
           '\n'.join(status),  ha='center', va='top')

Gives enter image description here

Edit: matplotlib 3.4.0

Since matplotlib 3.4.0 you can use axes.bar_label to automatically achieve a similar effect in a much cleaner way

fig, ax = plt.subplots()
rects = ax.bar('date', 'revenue', width=0.2, color='orange', data=dataF)
ax.bar_label(rects, ('\n'.join(i) for i in dataF["status"]), label_type='center')

produces enter image description here

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.