我使用了plt.barfrom,matplotlib.pyplot但在使文本適合在框外顯示文本的位置時遇到問題。所以,我需要在欄上方顯示不同字體大小和空格的文本。
for rect in barp1 barp2 barp3 barp4 barp5 barp6 barp7 barp8:
height = rect.get_height()
plt.text(rect.get_x() rect.get_width() / 2.0, height, f'{height:.2f}',fontsize=5, ha='center', va='bottom' ,rotation = 90)

uj5u.com熱心網友回復:
一些想法:
- 在文本前添加一個額外的空格,以創建自然填充
plt.margins(y=...)在垂直方向添加額外的空白(因為條的零是“粘性的”,只會添加頂部的空白)- 可以使頂部和右側的脊椎不可見,以防止文本被頂線觸摸或劃掉
ax.spines['left'].set_bounds(0, 100)可用于顯示 y 軸,精確到 100- a
FixedLocator可用于僅設定直到 100 的刻度
以下代碼顯示了所有這些組合。根據您的情況和偏好,您可以選擇其中的一個或多個。
from matplotlib import pyplot as plt
from matplotlib.ticker import FixedLocator
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.rand(2, 8) * 100)
ax = df.plot.bar(legend=False)
for bar in ax.patches:
height = bar.get_height()
ax.text(bar.get_x() bar.get_width() / 2.0, height, f' {height:.2f}', fontsize=10,
ha='center', va='bottom', rotation=90)
ax.margins(y=0.20)
for sp in ['top', 'right']:
ax.spines[sp].set_visible(False)
ax.spines['left'].set_bounds(0, 100)
ax.yaxis.set_major_locator(FixedLocator(np.arange(0, 101, 10)))
plt.tight_layout()
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438496.html
標籤:Python python-3.x matplotlib
上一篇:我在matplotlib中動態設定子圖數量的方式有什么不正確的
下一篇:子圖子圖
