使用 matplotlib 标记水平条 bar_label

Labeling horizontal bar using matplotlib bar_label

我想用 pyplot.barh()ax.bar_label 在每个柱上显示柱的值。

我已阅读文档 https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_label_demo.html,但没有帮助。请帮忙。

# Prepare & sort the data
df = pd.DataFrame({"coins": ["BTC", "ETH", "BNB", "XRP", "SOL", "ADA"],
                   "dominance": [42.08, 19.38, 3.68, 1.73, 1.55, 1.51]})
df = df.sort_values(by=["dominance"])

# Plot horizontal bar graph
plt.figure(figsize=[10, 9])
plt.barh(df.coins, df.dominance)

问题是 bar_label 是一项新功能,在 matplotlib 版本 3.4 或更高版本中可用 - 参考此 link。使用

检查 matplotlib 的版本
import matplotlib 
print('matplotlib: {}'.format(matplotlib.__version__))

升级到 v3.4 或使用 pip install matplotlib --upgrade 的最新版本。您需要将代码包含在您提供的 link 中,正如 JohanC 所提到的那样,并且能够看到条形标签