首页 > 解决方案 > matplotlib:改变条的位置

问题描述

我正在尝试在 x 轴上使用 2 个条形图在 matplotlib 中创建条形图子图。我创建了以下图像:

subplotted_bar

这是使用以下代码创建的:

import pandas as pd
import matplotlib.pyplot as plt

ydata1=pd.Series.from_array([451,505])
ydata2=pd.Series.from_array([839,286])

fig, (ax1, ax2) = plt.subplots(1,2,sharex='col',sharey='row')
xlabels = ['x1', 'x2']
ax1.bar(xlabels,ydata1, 0.4, align='center') #0.4 is width of bar
ax2.bar(xlabels,ydata2, 0.4, align='center')
plt.show()

我遇到的问题是我想调整条的位置,使它们对称并且与每个刻面的边缘等距,而不是在每个刻面的左右边缘(目前是这样)。有什么方法可以调整 matplotlib 中条形的位置,使它们对称?

谢谢

标签: pythonpandasmatplotlibsubplot

解决方案


要根据条形宽度和条数获得准确的边距,请注意:

  • 条的中心在位置0, 1, ..., N-1
  • 两个条之间的距离是1-bar_width
  • 第一个小节开始于0-bar_width/2; 要使条形和左边距之间的间距与条形本身之间的间距相等,可以将左边距设置为0-bar_width/2-(1-bar_width)
  • 同样,右边距可以设置为N-1+bar_width/2+(1-bar_width)
import matplotlib.pyplot as plt
import numpy as np

N = 8
ydata1 = np.random.randint(200, 800, N)
ydata2 = np.random.randint(200, 800, N)

fig, (ax1, ax2) = plt.subplots(1, 2, sharex='col', sharey='row')
xlabels = [f'x{i}' for i in range(1, N + 1)]
width = 0.4
ax1.bar(xlabels, ydata1, width, align='center')
ax2.bar(xlabels, ydata2, width, align='center')
margin = (1 - width) + width / 2
ax1.set_xlim(-margin, len(xlabels) - 1 + margin)
ax2.set_xlim(-margin, len(xlabels) - 1 + margin)
plt.show()

示例绘制 8 个条形图


推荐阅读