matplotlib:改变条形图的位置
matplotlib: changing position of bars
我正在尝试在 matplotlib 中创建一个条形图子图,在 x 轴上有 2 个条形图。我创建了以下图像:
这是使用以下代码创建的:
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()
我正在尝试在 matplotlib 中创建一个条形图子图,在 x 轴上有 2 个条形图。我创建了以下图像:
这是使用以下代码创建的:
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()