如何使条形图注释水平居中? [英] How to horizontally center a bar plot annotation?

查看:71
本文介绍了如何使条形图注释水平居中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  gender = ['M','F']数字= [男,女]条= plt.bar(性别,数字,宽度= 0.1,底部=无,align ='居中',数据=无)对于范围内的我(len(numbers)):plt.annotate(str(numbers [i]),xy =(gender [i],numbers [i]))plt.show() 

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

解决方案

  • 为了指定注释的水平对齐方式,请使用 ha 参数
    • I am creating a bar chart like this:

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

      I want to use plt.annotate to write the exact value on the top of the bar. However, the value is printed towards the right side. Is it possible to move it to the center?

      解决方案

      Option 1

      • From lists of values & categories

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

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

      Plot Output

      这篇关于如何使条形图注释水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆