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

Python3.8中matplotlib.pyplot.scatter绘图异常:部分数据点未连接

Python 3.8中Matplotlib散点+折线绘图数据点连接异常问题

在Python 3.8环境下使用matplotlib.pyplot绘制数据集时,出现数据点连接不一致的问题:随机间隔内的部分中间数据点未被折线连接,但另一部分数据点能正常连接。

问题代码

import matplotlib.pyplot as plt

def _plot_time_data(data):

    num_plots = 1
    fig, subplot = plt.subplots(num_plots, figsize=(30, num_plots*80), squeeze=False, tight_layout=True)           
    x = 0
    y = 0

    subplot[x][y].scatter(data["t"], data["value"],zorder=1)
    subplot[x][y].set_title("time vs data,",fontsize=15, fontweight='bold')
    subplot[x][y].set_xlabel("Time in seconds")
    subplot[x][y].set_ylabel("(-)L   PhaseShift[us]   R(+)",fontsize=15,fontweight='bold')
    subplot[x][y].plot(data["t"], data["value"], '.r-',scalex=True, scaley=True, zorder=2)
    subplot[x][y].margins(0)
    yl_lmt = (min(data["value"]) - abs(min(data["value"]))/2) if (min(data["value"]) - abs(min(data["value"]))/2) !=0 else -1
    yh_lmt = (max(data["value"]) + abs(max(data["value"]))/2) if (max(data["value"]) + abs(max(data["value"]))/2) !=0 else  1
    subplot[x][y].set_ylim(yl_lmt, yh_lmt)
    subplot[x][y].set_xlim(xStart, xStop)
    subplot[x][y].grid(linestyle='dotted', color='grey')

异常表现

绘图中折线在部分区间断开,仅显示散点标记;另一部分区间则正常通过折线连接所有散点。

问题原因与解决方案

核心原因

Matplotlib的plot函数会严格按照数据传入的顺序依次连接点。如果你的时间列data["t"]是乱序的,折线就会在乱序位置“跨区间跳转”,视觉上表现为部分点没被连接。

解决步骤

  1. 对数据按时间列排序:绘图前先将数据集按时间列升序排列,确保点的连接顺序符合时间逻辑。
  2. 补全未定义变量:代码中xStart和xStop未定义,需确保这两个变量有合法值(比如用数据的最小/最大时间)。

修改后的完整代码

import matplotlib.pyplot as plt

def _plot_time_data(data):
    # 关键:按时间列升序排序,保证点的连接顺序正确
    data = data.sort_values(by="t")
    
    num_plots = 1
    fig, subplot = plt.subplots(num_plots, figsize=(30, num_plots*80), squeeze=False, tight_layout=True)           
    x = 0
    y = 0

    subplot[x][y].scatter(data["t"], data["value"], zorder=1)
    subplot[x][y].set_title("时间 vs 数据", fontsize=15, fontweight='bold')
    subplot[x][y].set_xlabel("时间(秒)")
    subplot[x][y].set_ylabel("(-)L   相移[us]   R(+)", fontsize=15, fontweight='bold')
    subplot[x][y].plot(data["t"], data["value"], '.r-', scalex=True, scaley=True, zorder=2)
    subplot[x][y].margins(0)
    
    # 简化y轴范围计算
    min_val = data["value"].min()
    yl_lmt = min_val - abs(min_val)/2 if (min_val - abs(min_val)/2) != 0 else -1
    max_val = data["value"].max()
    yh_lmt = max_val + abs(max_val)/2 if (max_val + abs(max_val)/2) != 0 else 1
    subplot[x][y].set_ylim(yl_lmt, yh_lmt)
    
    # 用数据的时间范围设置x轴边界,避免未定义变量错误
    xStart = data["t"].min()
    xStop = data["t"].max()
    subplot[x][y].set_xlim(xStart, xStop)
    
    subplot[x][y].grid(linestyle='dotted', color='grey')
    plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 05:40:34