Python matplotlib画双Y轴图:柱状图折线图同轴对比
用Python matplotlib画双Y轴图,左轴柱右轴线,同时展示量级不同的两个指标,解决数值差太大折线看不清的问题,附完整代码。
场景痛点
做经营分析时经常要同时看"销售额"和"增长率",销售额是几十万,增长率是个位数百分比,画在同一个Y轴上折线会被压扁成一条直线,根本看不出趋势。用matplotlib的 twinx() 画双Y轴,左轴放柱子、右轴放折线,两个指标各用各的刻度,一张图就能同时展示。
用到的库
pip install matplotlib pandas
完整代码
# 导入库
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# 解决中文乱码
matplotlib.rcParams["font.sans-serif"] = ["SimHei", "Microsoft YaHei", "Arial Unicode MS"]
matplotlib.rcParams["axes.unicode_minus"] = False
def draw_dual_axis():
months = ["1月", "2月", "3月", "4月", "5月", "6月"]
sales = [120, 150, 180, 160, 210, 260] # 销售额(万元)
growth_rate = [0, 0.25, 0.20, -0.11, 0.31, 0.24] # 环比增长率
fig, ax1 = plt.subplots(figsize=(10, 6))
# 左Y轴:柱状图表示销售额
bars = ax1.bar(months, sales, color="#4C72B0", alpha=0.7, label="销售额")
ax1.set_xlabel("月份", fontsize=12)
ax1.set_ylabel("销售额(万元)", fontsize=12, color="#4C72B0")
ax1.tick_params(axis="y", labelcolor="#4C72B0")
# 在柱子顶部标数值
for bar in bars:
h = bar.get_height()
ax1.text(bar.get_x() + bar.get_width() / 2, h + 3,
f"{h}", ha="center", fontsize=9)
# 右Y轴:折线表示增长率
ax2 = ax1.twinx()
line = ax2.plot(months, growth_rate, color="#C44E52",
marker="o", linewidth=2, label="环比增长率")
ax2.set_ylabel("环比增长率", fontsize=12, color="#C44E52")
ax2.tick_params(axis="y", labelcolor="#C44E52")
# 把右轴格式化成百分比
ax2.yaxis.set_major_formatter(plt.FuncFormatter(lambda v, _: f"{v:.0%}"))
# 合并两个轴的图例
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(handles1 + handles2, labels1 + labels2, loc="upper left")
plt.title("月度销售额与环比增长率", fontsize=16)
plt.tight_layout()
plt.savefig("dual_axis.png", dpi=150)
plt.close()
print("双Y轴图已保存为 dual_axis.png")
if __name__ == "__main__":
draw_dual_axis()
代码讲解
fig, ax1 = plt.subplots()先创建左轴对象,ax1.bar()在左轴画柱状图。ax2 = ax1.twinx()关键一步:创建一个共享X轴、但Y轴独立的右轴对象,后续ax2.plot()画的折线会用右轴刻度。ax1.tick_params(labelcolor=...)让左右轴刻度文字颜色和柱子/折线对应,读图时不容易混淆。FuncFormatter把右轴小数格式化成百分比显示,0.25 显示成 25%。- 两个轴的图例要手动合并:分别取
get_legend_handles_labels()再拼到一起。
运行结果
当前目录生成 dual_axis.png,图中蓝色柱子是销售额(左轴),红色折线是增长率(右轴,百分比格式),柱顶有数值标注,左上角合并图例。一眼能看出5月销售额最高、增长率也最猛。
注意事项
- 双Y轴图容易误导读者,两个轴的起点都要从0开始,否则视觉对比会失真。
- 颜色要选对比度高的,柱子和折线颜色相近会读错轴。
- 一篇报告里双Y轴图别用太多,每个图最多两个轴,三轴以上基本没法看。

更新时间:2026-09-14 20:31:20
上一篇:Python matplotlib画折线图:从零绘制带标记的趋势曲线