Strange behaviour of bar chart when using twinx in Matplotlib

时间:2019-03-19 15:11:18

标签: python matplotlib

I have been battling this for too long, to the point that I'm pretty sure I don't understand the implementation of twinx in matplotlib

ok I have some code

import matplotlib.pyplot as plt

data1 = [5, 6, 6, 7]
err1 = [1, 1, 1, 1]
data2 = [0.5, 0.6]
err2 = [0.01, 0.01]

label1 = ['var1', 'var2', 'var3', 'var4']
label2 = ['var5', 'var6']

If I just want to plot data 1 everything is fine.

fig, ax1 = plt.subplots()
ax1.bar(label1, data1, yerr=err1, color='red')
plt.show()

This gives me a pretty chart enter image description here

If I want to add data 2 onto a second axis I lose columns and the order is also odd.

ax1.bar(label1, data1, yerr=err1, color='red')
ax2 = ax1.twinx()
ax2.bar(label2, data2, yerr=err2, color='blue')
plt.show()

Does not give me six columns but only 4 with two of the data1 columns now missing?

enter image description here

Obviously Im 100% sure its my fault, but please someone put me out of this misery...

2 个答案:

答案 0 :(得分:1)

问题在于您的条形重叠,因此您看到的条形少了两个。解决方案是使用定义明确的x值定位钢筋,然后在双轴上绘制后,分配x-tick标签。

import matplotlib.pyplot as plt

data1 = [5, 6, 6, 7]
err1 = [1, 1, 1, 1]
data2 = [0.5, 0.6]
err2 = [0.01, 0.01]

label1 = ['var1', 'var2', 'var3', 'var4']
label2 = ['var5', 'var6']

fig, ax1 = plt.subplots()
ax1.bar(range(len(label1)), data1, yerr=err1, color='red')

ax2 = ax1.twinx()
ax2.bar(range(4,6), data2, yerr=err2, color='blue')
ax2.set_xticks(range(6))
ax2.set_xticklabels(label1+label2)
plt.show()

enter image description here

答案 1 :(得分:1)

您也可以这样做:

label = ['var1', 'var2', 'var3', 'var4', 'var5', 'var6']
data1 = [5, 6, 6, 7, np.NaN, np.NaN]
data2 = [np.NaN, np.NaN, np.NaN, np.NaN, 0.5, 0.6]

这里的问题是matplotlib轴转换为整数:'var1'-> 1,'var2'-> 2等,而ax2是新轴,因此'var4'-> 1,'var5 '-> 2,则得到重叠。使双轴之间的类别相同可以消除这种混乱。