1 回答

TA貢獻1848條經驗 獲得超10個贊
從
matplotlib 3.4.2
,使用matplotlib.pyplot.bar_label
。
繪制列表和注釋
gender = ['M', 'F']
numbers = [1644, 1771]
plt.figure(figsize=(12, 6))
p = plt.bar(gender, numbers, width=0.1, bottom=None, align='center', data=None)
plt.bar_label(p)
plt.show()
用熊貓繪圖并注釋
將列表轉換為數據框并繪制pandas.DataFrame.plot
df = pd.DataFrame({'value': numbers, 'gender': gender})
ax = df.plot(x='gender', kind='bar', figsize=(12, 6), rot=0, legend=False, align='center', width=0.1)
ax.bar_label(ax.containers[0])
plt.show()
原始答案
為了指定注釋的水平對齊方式,使用
ha
參數matplotlib:文本屬性和布局
matplotlib:注釋
matplotlib.pyplot.annotate
根據JohanC的建議
一個技巧是使用
f'{value}\n'
as 字符串和未修改的value
(或numbers
)作為 y 位置,連同va='center'
.這也適用于
plt.text
.?或者,plt.annotation
接受以“點”或“像素”為單位的偏移量。
選項1
來自
lists
價值觀和類別
import matplotlib.pyplot as plt
gender = ['M', 'F']
numbers = [1644, 1771]
plt.figure(figsize=(12, 6))
bars = plt.bar(gender, numbers, width=0.1, bottom=None, align='center', data=None)
for i in range(len(numbers)):
? ? plt.annotate(f'{numbers[i]}\n', xy=(gender[i], numbers[i]), ha='center', va='center')
選項 2
來自
pandas.DataFrame
用于
pandas.DataFrame.iterrows
提取注釋所需的位置?x
。y
x
是分類'gender'
值y
是數字'value'
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'value': [1771, 1644], 'gender': ['F', 'M']})
plt.figure(figsize=(12, 6))
bars = plt.bar(df.gender, df.value, width=0.1, bottom=None, align='center', data=None)
for idx, (value, gender) in df.iterrows():
? ? plt.annotate(f'{value}\n', xy=(gender, value), ha='center', va='center')
繪圖輸出
添加回答
舉報