Matplotlib中两个柱状图重叠方向错误
我正在用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的位置,但这样y轴的标签也会反过来,这样我就不想要了。有没有简单的方法可以让matplotlib先画ax2,再画ax呢?
另外,右边的y轴标签被plt.tight_layout()切掉了。有没有办法在使用tight_layout的同时避免这个问题呢?
1 个回答
9
也许我不知道更好的方法,但你可以交换 ax
和 ax2
,同时也可以调整对应的 y
轴刻度的位置。
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
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+0.35, b, 0.45, color='#deb0b0')
ax2 = ax.twinx()
ax2.bar(ind+width, a, width, color='#b0c4de')
ax.set_xticks(ind+width+(width/2))
ax.set_xticklabels(a)
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
plt.tight_layout()
plt.show()
顺便说一下,你可以使用 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()
(结果和上面基本一样。)