慕桂英546537
从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.plotdf = 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 pltgender = ['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。yx是分类'gender'值y是数字'value'import pandas as pdimport matplotlib.pyplot as pltdf = 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')绘图输出