Python matplotlib中的两个条形图以错误的方式重叠

Python matplotlib中的两个条形图以错误的方式重叠,python,matplotlib,bar-chart,overlapping,Python,Matplotlib,Bar Chart,Overlapping,我正在用Python中的matplotlib创建条形图,但重叠的条形图有点问题: import numpy as np import matplotlib.pyplot as plt a = range(1,10) b = range(4,13) ind = np.arange(len(a)) width = 0.65 fig = plt.figure() ax = fig.add_subplot(111) ax.bar(ind+width, a, width, color='#b0c4d

我正在用Python中的matplotlib创建条形图,但重叠的条形图有点问题:

import numpy as np
import matplotlib.pyplot as plt

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))
width = 0.65

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

ax.bar(ind+width, a, width, color='#b0c4de')

ax2 = ax.twinx()
ax2.bar(ind+width+0.35, b, 0.45, color='#deb0b0')

ax.set_xticks(ind+width+(width/2))
ax.set_xticklabels(a)

plt.tight_layout()

我希望前面是蓝条,不是红条。到目前为止,我唯一能做到的就是切换ax和ax2,但随后ylabel也将被反转,这是我不想要的。有没有一种简单的方法告诉matplotlib在ax之前渲染ax2


此外,右侧的标签被plt.tight_layout()切断。在仍然使用紧凑布局的情况下,有没有办法避免这种情况?

也许有更好的方法,我不知道;但是,您可以交换
ax
ax2
,也可以交换相应的
y
-标记的位置

ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")


顺便说一句,您可以使用
align='center'
参数将条形图居中,而不是自己进行计算:

import numpy as np
import matplotlib.pyplot as plt

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(ind+0.25, b, 0.45, color='#deb0b0', align='center')

ax2 = ax.twinx()
ax2.bar(ind, a, 0.65, color='#b0c4de', align='center')

plt.xticks(ind, a)
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

plt.tight_layout()
plt.show()

(结果与上述基本相同。)

谢谢!这就成功了。也谢谢你的提示!我一直认为必须有一个更简单的方法。。
import numpy as np
import matplotlib.pyplot as plt

a = range(1,10)
b = range(4,13)
ind = np.arange(len(a))

fig = plt.figure()
ax = fig.add_subplot(111)
ax.bar(ind+0.25, b, 0.45, color='#deb0b0', align='center')

ax2 = ax.twinx()
ax2.bar(ind, a, 0.65, color='#b0c4de', align='center')

plt.xticks(ind, a)
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")

plt.tight_layout()
plt.show()