gpt4 book ai didi

python - matplotlib:改变条形的位置

转载 作者:行者123 更新时间:2023-12-04 09:48:04 26 4
gpt4 key购买 nike

我试图在 matplotlib 中创建一个条形图子图,在 x 轴上有 2 个条形图。我创建了以下图像:

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 中条形的位置,使它们对称?

谢谢

最佳答案

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

  • 条形的中心位于位置 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()

    example plot 8 bars

    关于python - matplotlib:改变条形的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62052017/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com