[英]matplotlib: changing position of bars
I am trying to create a bar chart subplot in matplotlib with 2 bar charts,on the x axis.我正在尝试在 matplotlib 中创建一个条形图子图,在 x 轴上有 2 个条形图。 I have created the following image:
我创建了以下图像:
This has been created with the following code:这是使用以下代码创建的:
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()
The problem I am having is I'd like to adjust the position of the bars so they are symmetrical and equally spaced from the edge of each facet, as opposed to on the left and right edges of each facet (as they currently are).我遇到的问题是我想调整 position 的条形,使它们对称并且与每个面的边缘等距,而不是在每个面的左右边缘(如它们当前那样)。 Is there any way to adjust the position of the bars in matplotlib so that they are symmetrical?
有什么方法可以调整matplotlib中的条形position使其对称吗?
Thanks谢谢
To obtain an exact margin depending on bar width and number of bars, note:要根据条宽和条数获得准确的边距,请注意:
0, 1, ..., N-1
0, 1, ..., N-1
1-bar_width
1-bar_width
0-bar_width/2
;0-bar_width/2
开始; to have an equal spacing between the bar and the left margin as between the bars themselves, the left margin can be set at 0-bar_width/2-(1-bar_width)
0-bar_width/2-(1-bar_width)
N-1+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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.