记录一下
首先,上代码
# 双y轴需要 sharex=True
fig, ax = plt.subplots(1, 1, sharex=True, figsize=(10, 10))
ax.plot(average,label='Explanaion #')
ax.set_ylim(0,1.6)
# 两个图都要legend, bbox_to_anchor 是调整legend 位置的,不设置的话,两个legend 会重叠在一起。
plt.legend(loc='lower left', bbox_to_anchor=(0.7, 0.95),
fancybox=True, shadow=True, ncol=3)
# 然后,画另一个图,在另一个y轴上,用 twinx
ax1 = ax.twinx()
x = (1+np.arange(14))
ax1.bar(x,exp_num,color='#2B647A', label='Averg. Card #', alpha=0.5/(i+1))
# 为了让两个y轴原点对齐,需要用 set_ylim, 并且计算两个y 轴能有公约数,比如4000,1.6都可以被4整除,否则的话,grid 会对不齐。
ax1.set_ylim(0,4000)
# 第二个图的legend.
plt.legend(loc='lower left', bbox_to_anchor=(0.7, 1),
fancybox=True, shadow=True, ncol=3)
plt.show()
见注释。