ROOT 最小 TGraph 绘图示例

这是如何在 ROOT 中绘制 TGraph 的最小示例。它绘制正弦波。

说明

sine_wave.cpp
#include <TGraph.h>
#include <TCanvas.h>
#include <TAxis.h>
#include <TApplication.h>
#include <cmath>
#include <memory>  // 用于 std::make_unique

int main(int argc, char **argv) {
    TApplication app("app", &argc, argv);

    // 点的数量
    const int nPoints = 100;
    double x[nPoints], y[nPoints];

    // 用 x 和 y 值填充数组(正弦波)
    for (int i = 0; i < nPoints; ++i) {
        x[i] = i * 0.1;            // x 值
        y[i] = sin(x[i]);           // y 值(x 的正弦)
    }

    // 使用 std::make_unique 为 TCanvas 和 TGraph 创建 unique_ptr
    auto canvas = std::make_unique<TCanvas>("canvas", "Sine Wave", 800, 600);
    auto graph = std::make_unique<TGraph>(nPoints, x, y);

    // 设置标题和坐标轴标签
    graph->SetTitle("Sine Wave;X-axis;Y-axis");
    graph->SetLineColor(kBlue);  // 设置线条颜色

    // 绘制图形
    graph->Draw("AL");  // "A" 表示坐标轴,"L" 表示线条

    // 运行应用程序以显示图形
    app.Run();

    return 0;
}

使用以下命令编译

compile_sine_wave.sh
g++ -o sine_wave sine_wave.cpp `root-config --cflags --glibs`

按类别查看类似文章: ROOT C/C++