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

Ubuntu 20.04运行matplotlibcpp示例报No axis错误求助

解决Ubuntu 20.04.2 LTS中matplotlibcpp plot_surface报"No axis"错误

问题重现

在Ubuntu 20.04.2 LTS系统中运行matplotlibcpp的3D曲面图示例代码时,触发如下错误:

terminate called after throwing an instance of 'std::runtime_error'
what(): No axis
Aborted

示例代码:

#include "../matplotlibcpp.h"

#include <cmath>

namespace plt = matplotlibcpp;

int main()
{
    std::vector<std::vector<double>> x, y, z;
    for (double i = -5; i <= 5;  i += 0.25) {
        std::vector<double> x_row, y_row, z_row;
        for (double j = -5; j <= 5; j += 0.25) {
            x_row.push_back(i);
            y_row.push_back(j);
            z_row.push_back(::std::sin(::std::hypot(i, j)));
        }
        x.push_back(x_row);
        y.push_back(y_row);
        z.push_back(z_row);
    }

    plt::plot_surface(x, y, z);
    plt::show();
}

错误来自matplotlibcpp.h第567行的检查逻辑:

if (!axis) throw std::runtime_error("No axis");

问题原因

matplotlibcpp的plot_surface是3D绘图接口,在Ubuntu 20.04的默认matplotlib配置环境中,不会自动创建3D坐标轴对象,导致代码中获取axis指针失败,触发异常。

解决方案

在调用plot_surface之前,显式创建图形窗口和3D坐标轴:

修改后的代码:

#include "../matplotlibcpp.h"

#include <cmath>

namespace plt = matplotlibcpp;

int main()
{
    std::vector<std::vector<double>> x, y, z;
    for (double i = -5; i <= 5;  i += 0.25) {
        std::vector<double> x_row, y_row, z_row;
        for (double j = -5; j <= 5; j += 0.25) {
            x_row.push_back(i);
            y_row.push_back(j);
            z_row.push_back(::std::sin(::std::hypot(i, j)));
        }
        x.push_back(x_row);
        y.push_back(y_row);
        z.push_back(z_row);
    }

    plt::figure(); // 创建图形窗口
    plt::axes3d(); // 初始化3D坐标轴
    plt::plot_surface(x, y, z);
    plt::show();
}

额外检查项

  • 确保系统已安装依赖的Python库:
    sudo apt install python3-matplotlib python3-numpy
    
  • 确认matplotlibcpp编译时链接了Ubuntu 20.04默认的Python3.8版本。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 08:32:26