如何在 Matplotlib 中顯示條形圖上方的百分比?
要在 Matplotlib 中顯示條形圖上方的百分比,我們可以採取以下步驟:
- 設定圖形大小並調整子圖之間和周圍的填充。
- 建立 x 和 y 資料點;初始化一個變數,寬度。
- 使用 subplots() 方法,建立一個圖形和一組子圖。
- 使用 x 和 y 資料點新增條形。
- 迭代條形補丁;使用 text() 方法,在條形上方放置文字。
- 使用 show() 方法,顯示圖形。
示例
from matplotlib import pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = [1, 2, 3, 4, 5]
y = [3, 4, 2, 1, 3]
width = 0.35
fig, ax = plt.subplots()
pps = ax.bar(x, y, width, align='center')
for p in pps:
height = p.get_height()
ax.text(x=p.get_x() + p.get_width() / 2, y=height+.10,
s="{}%".format(height),
ha='center')
plt.show()輸出

廣告
資料結構
聯網
RDBMS
作業系統
爪哇
iOS
HTML
CSS
安卓
蟒蛇
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP