【问题标题】:How to horizontally center a bar plot annotation如何水平居中条形图注释
【发布时间】:2020-11-22 08:46:51
【问题描述】:

我正在创建这样的条形图:

gender = ['M', 'F']
numbers = [males,females]
bars = plt.bar(gender, numbers, width=0.1, bottom=None, align='center', data=None)
for i in range(len(numbers)):
    plt.annotate(str(numbers[i]), xy=(gender[i],numbers[i]))
plt.show()

我想使用plt.annotate 在栏的顶部写出确切的值。但是,该值打印在右侧。可以移到中心吗?

【问题讨论】:

    标签: python matplotlib annotations bar-chart


    【解决方案1】:

    绘制列表和注释

    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 绘制和注释

    • 将列表转换为数据框并使用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()
    

    原答案

    选项 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

    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')
    

    绘图输出

    【讨论】:

      猜你喜欢
      • 2017-08-09
      • 2016-10-13
      • 2020-03-31
      • 2016-03-21
      • 1970-01-01
      • 2022-01-05
      • 1970-01-01
      • 2023-03-29
      • 2017-09-30
      相关资源
      最近更新 更多