如何在條形圖上的條形上方寫文字(Python Matplotlib)?
要在條形圖上的條形上方寫文字,我們可以採取以下步驟
- 設定圖形大小和調整子圖之間和周圍的填充。
- 建立年份、人口和x 的列表。初始化一個寬度變數。
- 使用 subplots() 方法建立一個圖形和一組子圖。
- 設定 y標籤、標題、xtickas 和 xtick標籤。
- 使用bar() 方法繪製條形,其中包含x、population 和 width 資料。
- 迭代條形補丁,並使用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 years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011] population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09, 439.23, 548.16, 683.33, 846.42, 1028.74] x = np.arange(len(years)) # the label locations width = 0.35 # the width of the bars fig, ax = plt.subplots() ax.set_ylabel('Population(in million)') ax.set_title('Years') ax.set_xticks(x) ax.set_xticklabels(years) pps = ax.bar(x - width / 2, population, width, label='population') 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()
輸出
廣告