【问题标题】:matplotlib: changing position of barsmatplotlib:改变条的位置
【发布时间】:2020-09-15 00:28:15
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: python pandas matplotlib subplot


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-18
      • 2013-09-30
      • 2021-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多