fig, ax1 = plt.subplots()
# 1.左边坐标及绘制柱状图
ax1.set_ylabel('box office')
ax1.set_ylim(0, 80000)
a = ax1.bar(x - 0.2, y1, width=0.2, color="#fc8251", label="box office")
# 2.右边坐标轴及绘制柱状图(注意:b、c后面有逗号,否则报错)
ax2 = ax1.twinx()
ax2.set_ylim(0, 50)
ax2.set_ylabel('price & person times')
b, = ax2.bar(x, y2, width=0.2, color="#5470c6", label="price")
c, = ax2.bar(x + 0.2, y3, width=0.2, color="#f9c956", label="person times")
# 3.双坐标轴的图注!!!
g = [a, b, c]
f = [l.get_label() for l in g]
plt.legend(g, f, fontsize=7)
plt.show()
如果报错:list‘ object has no attribute ‘get_label‘
这个是因为第二个y轴后面每有加逗号,此时加上逗号即可。
# 2.右边坐标轴及绘制柱状图(注意:b、c后面有逗号,否则报错)
ax2 = ax1.twinx()
ax2.set_ylim(0, 50)
ax2.set_ylabel('price & person times')
b, = ax2.bar(x, y2, width=0.2, color="#5470c6", label="price") # 注意:b、c后面有逗号
c, = ax2.bar(x + 0.2, y3, width=0.2, color="#f9c956", label="person times") # 注意:b、c后面有逗号