如何在matplotlib中将条形图的xticks居中?

梦想家911

我正在按照本教程在我的条形图链接中添加价值

博客中显示的代码是这样写的

from matplotlib import pyplot as plt
import numpy as np

years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09, 439.23, 548.16, 683.33, 846.42, 1028.74]

x = np.arange(len(years)) # the label locations
width = 0.35 # the width of the bars

fig, ax = plt.subplots()

ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)

pps = ax.bar(x - width/2, population, width, label='population')
for p in pps:
   height = p.get_height()
   ax.annotate('{}'.format(height),
      xy=(p.get_x() + p.get_width() / 2, height),
      xytext=(0, 3), # 3 points vertical offset
      textcoords="offset points",
      ha='center', va='bottom')

plt.show()

所以,输出变成这样

在此处输入图片说明

但是,我刚刚意识到条形图中的 xticks 没有居中

在此处输入图片说明

我的问题 - 有人知道如何将 xticks 居中吗?

我试图找到解决方案,但还没有找到

任何帮助将不胜感激,谢谢

亨利·埃克

matplotlib3.4.0 或更新版本bar_label中可以使用来代替annotate

import numpy as np
from matplotlib import pyplot as plt

years = [1901, 1911, 1921, 1931, 1941, 1951, 1961, 1971, 1981, 1991, 2001, 2011]
population = [237.4, 238.4, 252.09, 251.31, 278.98, 318.66, 361.09, 439.23,
              548.16, 683.33, 846.42, 1028.74]

# Create Tick Locations
x = np.arange(len(years))
# Plotting
fig, ax = plt.subplots(figsize=(10, 6))
# Do not offset the values of x to center labels (default)
ax.bar(x, population, width=.35, label='population')

# Labels, ticks, etc.
ax.set_ylabel('Population(in million)')
ax.set_title('Years')
ax.set_xticks(x)
ax.set_xticklabels(years)

# Add Bar Labels
for c in ax.containers:
    ax.bar_label(c)

plt.show()

阴谋

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章