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

如何使用matplotlibcpp绘制含图例与标记的复杂对数图?

使用matplotlibcpp在C++中实现带图例和标记的Matplotlib对数图

原Python实现代码

import matplotlib.pyplot as plt
import numpy as np

x = np.logspace(1, 2, 100)
y = x ** 2

plt.loglog(x, y, 'bo--', label='y = x²')
plt.legend()
plt.title('对数坐标图示例')
plt.xlabel('X轴(对数)')
plt.ylabel('Y轴(对数)')
plt.show()

预期效果

Matplotlib对数图效果

我的C++尝试代码(问题:无法添加图例和标记)

#include "matplotlibcpp.h"
#include <vector>
#include <cmath>

namespace plt = matplotlibcpp;

int main() {
    std::vector<double> x, y;
    for(double i = 1; i <= 100; ++i) {
        x.push_back(i);
        y.push_back(pow(i, 2));
    }

    // 问题:plot函数无法传递标记、图例相关参数
    plt::plot(x, y);
    plt::show();
    return 0;
}

解决方法

matplotlibcpp完全支持通过格式字符串和额外参数实现标记、图例以及对数轴设置,以下是修正后的代码:

#include "matplotlibcpp.h"
#include <vector>
#include <cmath>

namespace plt = matplotlibcpp;

int main() {
    // 生成对应数据
    std::vector<double> x, y;
    for(double i = 1; i <= 100; ++i) {
        x.push_back(i);
        y.push_back(pow(i, 2));
    }

    // 1. 绘制带标记的曲线,同时指定图例标签
    // 格式字符串"bo--"对应:蓝色(b)、圆圈标记(o)、虚线(--)
    // 通过键值对参数设置图例标签
    plt::plot(x, y, "bo--", {{"label", "y = x²"}});

    // 2. 设置对数坐标轴
    plt::xscale("log");
    plt::yscale("log");

    // 3. 显示图例
    plt::legend();

    // 可选:添加标题和坐标轴标签
    plt::title("对数坐标图示例");
    plt::xlabel("X轴(对数)");
    plt::ylabel("Y轴(对数)");

    plt::show();
    return 0;
}

关键说明

  • 标记与线条样式:使用和Matplotlib一致的格式字符串,比如"ro-"表示红色实心标记+实线,"g^:"表示绿色三角标记+点线,规则与Python版Matplotlib完全一致。
  • 图例设置:通过plot函数的额外键值对参数{{"label", "图例文本"}}指定标签,再调用plt::legend()显示图例;也可以用plt::named_plot("图例文本", x, y, "格式字符串")替代,效果相同。
  • 对数轴设置:直接调用plt::xscale("log")和plt::yscale("log")即可切换为对数坐标轴。

编译注意事项

编译时需要链接对应版本的Python库,例如针对Python3.8的g++命令:

g++ -std=c++11 log_plot.cpp -o log_plot -I/usr/include/python3.8 -lpython3.8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:43:23