[英]Bar text is above the plot matplotlib
Each bar on my plot has a value above ( ax.text
).我的图中的每个条形都有一个高于 (
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?如何调整绘图大小(
figsize
没有帮助)以便文本位于图片内?
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()
You have to use plt.ylim(ymin, ymax)
to change minimum and maximum of you showed Y
axis.您必须使用
plt.ylim(ymin, ymax)
来更改您显示的Y
轴的最小值和最大值。 I added two next lines for both plots, they add extra 10%
of Y
range at the top:我为两个图添加了下两条线,它们在顶部添加了额外的
Y
范围的10%
:
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.您还可以为两个图添加不同的(不是两个
10%
)百分比的数量,以避免它们发生冲突。
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:结果:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.