简体   繁体   中英

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 picture 在此处输入图片说明

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:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM