You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于Pandas DataFrame使用Matplotlib绘制双Y轴图表?

如何用Pandas DataFrame实现Matplotlib双Y轴绘图

我来帮你把Matplotlib的双Y轴示例适配到你的Pandas DataFrame上,其实改动很小,咱们直接针对你的场景调整代码就行:

首先,先确认你的数据读取代码没问题(注意Windows路径的反斜杠要转义,或者用原始字符串避免解析错误):

import pandas as pd
import matplotlib.pyplot as plt

# 读取并处理数据,注意路径的写法
pumpDf = pd.read_csv(r'C:\Python Scripts\data.csv', index_col='Date', parse_dates=True)
pumpDf = pumpDf.truncate(before='12/17/2017', after='12/31/2017')

接下来,你可以保留Matplotlib示例里的两个工具函数(two_scales和color_y_axis),只需要修改数据传入的部分——因为你的DataFrame已经自带时间索引,直接用它替代示例里的NumPy数组即可:

def two_scales(ax1, time, data1, data2, c1, c2):
    """
    Parameters
    ----------
    ax1 : axis
        Axis to put two scales on
    time : array-like
        x-axis values for both datasets(这里用你的DataFrame时间索引)
    data1: array-like
        Data for left hand scale(对应你的DP列)
    data2 : array-like
        Data for right hand scale(对应你的pump30列)
    c1 : color
        Color for line 1
    c2 : color
        Color for line 2

    Returns
    -------
    ax1 : axis
        Original axis
    ax2 : axis
        New twin axis
    """
    ax2 = ax1.twinx()
    ax1.plot(time, data1, color=c1)
    ax1.set_xlabel('Date')
    ax1.set_ylabel('DP')
    ax2.plot(time, data2, color=c2)
    ax2.set_ylabel('pump30')
    return ax1, ax2

def color_y_axis(ax, color):
    """Color your axes."""
    for t in ax.get_yticklabels():
        t.set_color(color)
    return None

# -------------------------- 重点修改的调用部分 --------------------------
# 创建画布和轴,可指定大小让图表更美观
fig, ax = plt.subplots(figsize=(10, 6))

# 传入你的DataFrame数据:用时间索引作为x轴,DP和pump30分别作为左右轴数据
ax1, ax2 = two_scales(ax, pumpDf.index, pumpDf['DP'], pumpDf['pump30'], 'darkred', 'steelblue')

# 给轴上色
color_y_axis(ax1, 'darkred')
color_y_axis(ax2, 'steelblue')

# 添加图例,让图表逻辑更清晰
ax1.legend(['DP'], loc='upper left')
ax2.legend(['pump30'], loc='upper right')

# 自动调整布局,避免标签被截断
plt.tight_layout()
plt.show()

关键改动说明:

  • 用pumpDf.index替代了示例中的NumPy时间数组t——你的DataFrame索引已经是解析好的时间序列,直接复用即可
  • 用pumpDf['DP']和pumpDf['pump30']替换了示例中的s1和s2,直接调用DataFrame的列数据就能适配
  • 修改了轴标签为你实际的列名,替换了示例里的默认通用标签
  • 增加了画布大小设置、图例和tight_layout(),让最终的图表可读性更强

另外补充个小提醒:如果你的时间索引格式和示例里的t不太一样也没关系,Matplotlib会自动识别Pandas的时间序列并正确渲染x轴。

内容的提问来源于stack exchange,提问作者bbartling

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:07:12