user12628549
user12628549

Reputation: 182

Bar text is above the plot matplotlib

Each bar on my plot has a value above (ax.text). But if the bar is tall, the text is above the plot. How can I resize the plot (figsize doesn't help) so that the text will be inside the picture?

import numpy as np

x = np.arange(len(l))
l = [200,240,302,371,478]
l2 = [17, 20, 26, 23, 29]

fig = plt.figure(figsize=(10,8))
ax1 = fig.add_subplot(111)
ax1.bar(x,l)


totals=[]
for i in ax1.patches:
    totals.append(i.get_height())

total = sum(totals)


for i in ax1.patches:

    ax1.text(i.get_x()+0.1, i.get_height()+20, str(int(i.get_height())), fontsize=14, color='black')


ax2 = ax1.twinx()
ax2.plot(l2, color = 'b')

for x1, y1 in zip(x, l2):
    ax2.annotate(str(y1)+'%', xy = (x1-0.1,y1+1 ))
    
ax2.grid(False)
ax2.set_yticks([-25, -10, -5,0,5,10,15,20,25,30])
plt.show()

UPD: added code and pictureenter image description here

Upvotes: 1

Views: 459

Answers (1)

Arty
Arty

Reputation: 16737

You have to use plt.ylim(ymin, ymax) to change minimum and maximum of you showed Y axis. I added two next lines for both plots, they add extra 10% of Y range at the top:

ymin, ymax = plt.ylim()
plt.ylim(ymin, ymax + 0.1 * (ymax - ymin))

You may also add different (not both 10%) amount of percents for both plots to avoid collision of them.

Full fixed code below:

import numpy as np, matplotlib.pyplot as plt

l = [200,240,302,371,478]
l2 = [17, 20, 26, 23, 29]
x = np.arange(len(l))

fig = plt.figure(figsize=(10,8))
ax1 = fig.add_subplot(111)
ax1.bar(x,l)
# Next two lines added
ymin, ymax = plt.ylim()
plt.ylim(ymin, ymax + 0.1 * (ymax - ymin))


totals=[]
for i in ax1.patches:
    totals.append(i.get_height())

total = sum(totals)


for i in ax1.patches:

    ax1.text(i.get_x()+0.1, i.get_height()+20, str(int(i.get_height())), fontsize=14, color='black')


ax2 = ax1.twinx()
ax2.plot(l2, color = 'b')

for x1, y1 in zip(x, l2):
    ax2.annotate(str(y1)+'%', xy = (x1-0.1,y1+1 ))
    
ax2.grid(False)
ax2.set_yticks([-25, -10, -5,0,5,10,15,20,25,30])
# Next two lines added
ymin, ymax = plt.ylim()
plt.ylim(ymin, ymax + 0.1 * (ymax - ymin))
plt.show()

Result:

enter image description here

Upvotes: 2

Related Questions