matplotlib折线图与柱状图(条形图)同时显示,数据参考各自的轴线

说明

如下图:

代码


import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['Microsoft YaHei']

# 双y轴需要 sharex=True
fig, ax1 = plt.subplots(sharex=True)

# 星期
names = ['1月', '2月', '3月', '4月', '5月', '6月']

# 柱状图的数据
heights2 = [105, 34, 97, 57,42,18]

# 设置左侧y轴最小值、最大值
ax1.set_ylim(bottom=0, top=120)
# 通过ax1绘制柱状图,柱子的高度是参考ax1的最大值、最小值
ax1.bar(names, heights2, width=0.8, color='#2249b1', label='出让面积(万m²)')


# 显示右侧y轴
ax2 = ax1.twinx()
# 设置右侧y轴最小值、最大值
ax2.set_ylim(bottom=0, top=500)

# 折线图的数据
heights = [420, 148, 330, 168,250,45]
# 通过ax2绘制折线图,数据是参考ax2的最大值、最小值
ax2.plot(names, heights, marker='o', color='#d37e84', label='出让金额(亿元)')

ax1.legend()
# 显示ax2图表中的图例,往下移动0.1,否则两个图例会叠加显示
ax2.legend(bbox_to_anchor=(0, -0.1, 1, 1))

plt.title("各区域土地出让面积、成交金额对比")

# 显示窗口,必须写
plt.show()

原文出处:/show_1GW2VPJoDNB.html