如何使文本适合 matplotlib 中的条形图?

How to fit the text above the bars plot in matplotlib?

我使用了 matplotlib.pyplot 中的 plt.bar,但我在使文本适合显示框外文本的位置时遇到问题。所以,我需要在栏上方显示不同字体大小和 space.

的文本
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)

一些想法:

  • 在文本前添加额外的 space,以创建自然填充
  • plt.margins(y=...) 在垂直方向添加额外的白色space(因为条形的零是“粘性”的,所以只会添加顶部的白色space)
  • 可以使顶部和右侧的书脊不可见,以防止文本被顶行触摸或划掉
  • ax.spines['left'].set_bounds(0, 100) 可用于显示 y-axis 正好达到 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()