簡體   English   中英

條形文本位於繪圖 matplotlib 上方

[英]Bar text is above the plot matplotlib

我的圖中的每個條形都有一個高於 ( ax.text ) 的值。 但是,如果條形圖很高,則文本位於圖上方。 如何調整繪圖大小( 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()

UPD:添加代碼和圖片在此處輸入圖片說明

您必須使用plt.ylim(ymin, ymax)來更改您顯示的Y軸的最小值和最大值。 我為兩個圖添加了下兩條線,它們在頂部添加了額外的Y范圍的10%

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

您還可以為兩個圖添加不同的(不是兩個10% )百分比的數量,以避免它們發生沖突。

完整的固定代碼如下:

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()

結果:

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM