pandas结合matplotlib绘制双y轴散点图如何指定系列对应坐标轴
双Y轴散点图实现方案
问题背景
需要在单张matplotlib图表中同时配置左侧、右侧两个Y轴:
- 基于pandas读取Excel指定范围数据存入DataFrame后绘图
- 预期效果:PM3散点系列绑定右侧Y轴,PM1、AFS散点系列保留在左侧Y轴
- 现有代码可正常绘制三个字段的散点,但调用
twinx()未达到轴分离的预期效果

原有代码
import pandas as pd import matplotlib.pyplot as plt import numpy as np testproject = r"C:\Users\223070186\Documents\PleaseWork.xlsx" var = pd.read_excel(testproject, sheet_name ="Test1") df = pd.DataFrame(var, columns = ["Time", "PM1", "PM3", "AFS"]) df2 = df.iloc[1108:1142, 0:4] ax1 = df2.plot(kind = "scatter", x = "Time", y = "PM1", color = "r") ax2 = df2.plot(kind = "scatter", x="Time", y = "PM3", color = "purple", ax =ax1) ax3 = df2.plot(kind = "scatter", x = "Time", y= "AFS", color = "orange", ax = ax2) plt.xlabel("Time") plt.ylabel("PM1, PM3, AFS") plt.title("Time vs PM1, PM3, AFS splits") plt.show(ax1 == ax2 == ax3)
问题原因
原有代码中三个散点系列全部绑定到了同一个左轴实例上:ax2、ax3本质都是和ax1指向同一个坐标轴对象,没有真正生成独立的右轴,哪怕调用twinx()如果不把对应系列绑定到新生成的右轴实例上,也不会实现轴分离效果。另外plt.show(ax1 == ax2 == ax3)是无效写法,传入的布尔值参数不会对绘图产生任何作用。
修正后可运行代码
import pandas as pd import matplotlib.pyplot as plt import numpy as np testproject = r"C:\Users\223070186\Documents\PleaseWork.xlsx" var = pd.read_excel(testproject, sheet_name ="Test1") df = pd.DataFrame(var, columns = ["Time", "PM1", "PM3", "AFS"]) df2 = df.iloc[1108:1142, 0:4] # 初始化画布与左侧主坐标轴 fig, ax1 = plt.subplots() # 左轴绘制PM1、AFS两个系列 df2.plot(kind="scatter", x="Time", y="PM1", color="r", ax=ax1, label="PM1") df2.plot(kind="scatter", x="Time", y="AFS", color="orange", ax=ax1, label="AFS") # 配置左轴标签 ax1.set_xlabel("Time") ax1.set_ylabel("PM1, AFS") # 生成共享X轴的右侧独立Y轴 ax2 = ax1.twinx() # 右轴绘制PM3系列 df2.plot(kind="scatter", x="Time", y="PM3", color="purple", ax=ax2, label="PM3") # 配置右轴标签 ax2.set_ylabel("PM3") # 合并两个轴的图例,避免图例只显示单个轴的内容 handles_left, labels_left = ax1.get_legend_handles_labels() handles_right, labels_right = ax2.get_legend_handles_labels() ax1.legend(handles_left + handles_right, labels_left + labels_right, loc="best") plt.title("Time vs PM1, PM3, AFS splits") plt.show()
关键注意点
- 所有需要显示在左侧Y轴的散点系列,统一指定
ax=ax1(左轴实例);需要显示在右侧Y轴的系列,统一指定ax=ax2(twinx()生成的右轴实例),不要链式赋值覆盖轴变量 - 双Y轴默认不会自动合并图例,需要手动收集两个轴的图例句柄做合并
plt.show()不需要传入任何参数,直接调用即可渲染显示图表
内容的提问来源于stack exchange,提问作者kingjcp44
相关产品推荐
相关产品推荐

