【问题标题】:How to center the xticks from a bar chart in matplotlib?如何在 matplotlib 中将条形图中的 xticks 居中?
【发布时间】:2021-09-24 19:20:37
【问题描述】:

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

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

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 居中吗?

我试图找到解决方案,但尚未找到

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

【问题讨论】:

  • 只是pps = ax.bar(x, population, width, label='population') 没有偏移x?
  • 好吧,再次感谢@HenryEcker

标签: python numpy matplotlib bar-chart xticks


【解决方案1】:

matplotlib 3.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()

【讨论】:

  • 现在我要去看看matplotlib 的最新消息,谢谢分享!似乎您可以使用 bar_container = ax.bar(...); ax.bar_label(bar_container) 而不是从 Axes 对象中获取 bar_container 。但是很高兴知道这一点!
  • 是的 在这个例子中只有一个容器。但是,如果您有多个容器(例如堆叠条形图),则需要迭代。我喜欢采用迭代方法,以便它(几乎)总是有效。
【解决方案2】:

imo 该教程使绘图变得比它需要的更混乱。您很少需要从情节上的艺术家那里获取坐标。直接使用您的数据:

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_values = np.arange(len(years))
fig, ax = plt.subplots(figsize=(12, 4))

ax.bar(x_values, population, width=.35, label='population')
for x, y in zip(x_values, population):    
    ax.annotate(
        str(y),        # label is our y-value as a string
        xy=(x, y),
        xytext=(0, 3), # 3 points vertical offset
        textcoords="offset points",
        ha='center', 
        va='bottom'
    )
    
    
ax.set_xticks(x_values)
ax.set_xticklabels(years)
ax.set_ylim(0, 1200)

plt.show()

【讨论】:

    猜你喜欢
    • 2023-03-26
    • 2012-05-04
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多