本文介绍了如何将条形图注释水平居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在创建这样的条形图:
gender = ['M','F']数字 = [男性,女性]条= plt.bar(性别,数字,宽度= 0.1,底部=无,对齐=中心",数据=无)对于范围内的我(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?解决方案- In order to specify the horizontal alignment of the annotation, use the
ha
parameter - 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.annotation
accepts an offset in 'points' or in 'pixels'.
- A trick is to use
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 thex
andy
location needed for the annotations.x
being the categorical'gender'
valuey
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
这篇关于如何将条形图注释水平居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
- In order to specify the horizontal alignment of the annotation, use the
-