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

Gnuplot绘图点数量异常:多余点出现问题排查

问题:Gnuplot绘制5组坐标却显示6个点的排查与解决

问题描述

通过C++程序生成包含5组坐标的coordinate.txt,调用Gnuplot的linespoint模式绘制PNG图时,结果出现6个点(预期5个),且存在单个坐标显示两个点的情况。坐标文件内容如下:

5 2
2 4
3 6
1 8
5 10

原因分析

  • 坐标文件缺少结尾换行符:代码中最后一行坐标5 10未添加换行符,部分Gnuplot版本读取无结尾换行的文件时,会重复解析最后一行数据,导致最后一个点被绘制两次,总点数变为6。
  • 错误使用-persist选项:generateImg函数中调用gnuplot -persist,但-persist是用于保持交互式图形窗口的选项,与set terminal png(输出到文件)冲突,可能触发重复绘制逻辑。
  • 无效的终端尺寸设置:generateVisualizeTerminal中设置set terminal dumb size 0,0,该尺寸无效,可能导致Gnuplot解析命令异常,间接影响后续绘图。

解决方案

  1. 给坐标文件最后一行添加换行符:确保所有数据行都以换行结束,避免Gnuplot解析错误。
  2. 移除-persist选项:生成PNG文件时无需保持交互式窗口,改用普通的gnuplot调用。
  3. 统一管道函数:Windows环境下统一使用_popen/_pclose,避免混合调用popen/_popen导致的异常。
  4. 设置合理的终端尺寸:给dumb终端设置有效尺寸(如80,24),避免解析异常。

修正后的代码

#include <iostream>
#include <fstream>
#include <cstdlib>

bool generateImg(){
    // 移除-persist选项,Windows环境统一使用_popen
    FILE* gnuplotPipe = _popen("gnuplot", "w");
    if (!gnuplotPipe) {
        std::cerr << "Error opening Gnuplot pipe." << std::endl;
        return false;
    }

    fprintf(gnuplotPipe, "set terminal png\n");
    fprintf(gnuplotPipe, "set output 'graph.png'\n");
    fprintf(gnuplotPipe, "plot 'coordinate.txt' using 1:2 with linespoint pt 7 ps 2\n");
    
    _pclose(gnuplotPipe);

    return true;
}

bool generateVisualizeTerminal(){
    // Windows环境统一使用_popen/_pclose
    FILE* gnuplotPipe = _popen("gnuplot", "w");
    if (!gnuplotPipe) {
        std::cerr << "Error opening Gnuplot pipe." << std::endl;
        return false;
    }

    // 设置有效dumb终端尺寸
    fprintf(gnuplotPipe, "set terminal dumb size 80,24\n");
    fprintf(gnuplotPipe, "plot 'coordinate.txt' with lines\n");

    _pclose(gnuplotPipe);

    return true;
}

int main() {
    std::ofstream dataFile("coordinate.txt");
    if (!dataFile) {
        std::cerr << "Error opening data file." << std::endl;
        return 1;
    }

    dataFile << "5 2\n";
    dataFile << "2 4\n";
    dataFile << "3 6\n";
    dataFile << "1 8\n";
    dataFile << "5 10\n"; // 添加结尾换行符
    dataFile.close();

    generateVisualizeTerminal();
    generateImg();

    return 0;
}

验证步骤

  1. 编译并运行修正后的程序,检查生成的coordinate.txt,确认最后一行5 10后存在换行符。
  2. 打开生成的graph.png,查看点数是否为5个,且无重复点。
  3. 观察终端输出的字符画图形,确认线条连接正确,无重复点。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 03:00:10