Con*_*nti 5 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='#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()
Run Code Online (Sandbox Code Playgroud)
我希望蓝色条纹在前面,而不是红色条纹.到目前为止,我设法做到的唯一方法是切换ax和ax2,但是ylabels也将被反转,这是我不想要的.是不是有一种简单的方法告诉matplotlib在ax之前渲染ax2?
此外,右侧的ylabels被plt.tight_layout()切断.有没有办法在仍然使用tight_layout时避免这种情况?
也许有一种我不了解的更好的方式; 但是,您可以交换ax
并且ax2
还可以交换相应的y
-ticks 的位置
ax.yaxis.set_ticks_position("right")
ax2.yaxis.set_ticks_position("left")
Run Code Online (Sandbox Code Playgroud)
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()
Run Code Online (Sandbox Code Playgroud)
顺便说一句,您可以使用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()
Run Code Online (Sandbox Code Playgroud)
(结果与上面的结果基本相同.)