How to horizontally center a bar plot annotation?

落花浮王杯 提交于 2021-02-11 12:44:10

问题


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?


回答1:


  • In order to specify the horizontal alignment of the annotation, use the ha parameter
    • matplotlib: Text Properties & Layout
    • matplotlib: Annotations
    • matplotlib.pyplot.annotate
  • As per the suggestion from JohanC
    • A trick is to use f'{value}\n' as a string and the unmodified value (or numbers) as y position, together with va='center'.
    • This also works with plt.text. Alternatively, plt.annotation accepts an offset in 'points' or in 'pixels'.

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

  • From a pandas.DataFrame
  • Use pandas.DataFrame.iterrows to extract the x and y location needed for the annotations.
    • x being the categorical 'gender' value
    • y being the numeric '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')

Plot Output



来源:https://stackoverflow.com/questions/63209883/how-to-horizontally-center-a-bar-plot-annotation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!