问题
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
haparameter- 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 unmodifiedvalue(ornumbers) as y position, together withva='center'. - This also works with
plt.text. Alternatively,plt.annotationaccepts an offset in 'points' or in 'pixels'.
- A trick is to use
Option 1
- From
listsof 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
xandylocation needed for the annotations.xbeing the categorical'gender'valueybeing 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