Python 在多条形图上移动条形位置

Python 在多条形图上移动条形位置,python,matplotlib,bar-chart,Python,Matplotlib,Bar Chart,对于python matplotlib问题,大量搜索并没有产生有效的解决方案。我肯定我错过了一些简单的事情 MWE: 生成: 无论我使用什么参数,左边的第一个条都会被切断。如果我只画一个条(即不是条簇),这些条就不会被切断,事实上两边都有很好的空白 我硬编码了这个MWE的数据;然而,我正试图找到一种通用的方法来确保正确的对齐,因为我可能会生成很多这样的图,在x轴上有不同数量的项目,每个簇中可能有不同数量的条 如何移动条形图,使其在x轴上的间距正确,且具有均匀的空白?这取决于您在绘图中放置的宽度

对于python matplotlib问题,大量搜索并没有产生有效的解决方案。我肯定我错过了一些简单的事情

MWE:

生成:

无论我使用什么参数,左边的第一个条都会被切断。如果我只画一个条(即不是条簇),这些条就不会被切断,事实上两边都有很好的空白

我硬编码了这个MWE的数据;然而,我正试图找到一种通用的方法来确保正确的对齐,因为我可能会生成很多这样的图,在x轴上有不同数量的项目,每个簇中可能有不同数量的条


如何移动条形图,使其在x轴上的间距正确,且具有均匀的空白?

这取决于您在绘图中放置的宽度。放一些
xlim

import pandas as pd
import matplotlib.pyplot as plt

#MWE plot
T = [1, 2, 3, 4, 5, 6]
n = len(T)
d1 = list(zip([500]*n, [250]*n))
d2 = list(zip([250]*n, [125]*n))

df1 = pd.DataFrame(data=d1, index=T)
df2 = pd.DataFrame(data=d2, index=T)

fig = plt.figure()
ax = fig.add_subplot(111)

df1.plot(kind='bar', stacked=True, align='edge', width=-0.4, ax=ax)
df2.plot(kind='bar', stacked=True, align='edge', width=0.4, ax=ax)   
plt.xlim(-.4,5.4) 
plt.show()


希望它能起作用

这确实管用,但是……你怎么知道用什么数字?我得到了条形宽度的系数,但是你怎么知道总限制应该是5呢?
-.4
来自
df1.plot()
的宽度,而
5.4
来自另一个。您需要假设您的数组是根据索引绘制的,而不是您在
T
数组中放置的内容。所以
-.4
来自
0.0-.4=.-4
。与
5.4
相同,它来自
5.0+.4=5.4
。我希望我帮助过你<代码>@Jennifer
import pandas as pd
import matplotlib.pyplot as plt

#MWE plot
T = [1, 2, 3, 4, 5, 6]
n = len(T)
d1 = list(zip([500]*n, [250]*n))
d2 = list(zip([250]*n, [125]*n))

df1 = pd.DataFrame(data=d1, index=T)
df2 = pd.DataFrame(data=d2, index=T)

fig = plt.figure()
ax = fig.add_subplot(111)

df1.plot(kind='bar', stacked=True, align='edge', width=-0.4, ax=ax)
df2.plot(kind='bar', stacked=True, align='edge', width=0.4, ax=ax)   
plt.xlim(-.4,5.4) 
plt.show()