如何使用CImg在同一图中绘制多阶第一类贝塞尔函数曲线
CImg多曲线同图绘制实现说明
完全支持多曲线同图绘制需求,CImg内置的display_graph()接口原生适配多通道数据的绘图逻辑,每个数据通道会被识别为一条独立曲线,自动分配区分色、生成坐标轴适配与图例,完全匹配你预期的多曲线展示效果。
核心实现逻辑
你当前的代码仅生成了1通道的CImg对象存储单条贝塞尔曲线,只要做几处调整即可实现多曲线绘制:
- 将单通道CImg替换为通道数等于待绘制贝塞尔阶数数量的多通道CImg对象
- 循环计算每个阶数的贝塞尔函数采样值,填充到对应通道的数组中
- 调用
display_graph()时传入对应每条曲线的图例标签即可
修改后参考代码
#include "libs/CImg-master/CImg.h" #include <iostream> #include <fstream> #include <vector> #include <boost/math/special_functions/bessel.hpp> using namespace cimg_library; using namespace std; int main(int argc, char** const argv) { cimg_usage("Simple plotter of mathematical formulas"); const char *const plot_title = cimg_option("-t", "First kind Bessel Function", "Plot title"); const float x0 = cimg_option("-x0", -5.0f, "Minimal X-value"); const float x1 = cimg_option("-x1", 5.0f, "Maximal X-value"); const int resolution = cimg_option("-r", 5000, "Plot resolution"); const unsigned int nresolution = resolution>1 ? resolution : 5000; const unsigned int plot_type = cimg_option("-p", 1, "Plot type"); const unsigned int vertex_type = cimg_option("-v", 0, "Vertex type"); // 设为0仅显示平滑曲线,无顶点标记 // 自定义待绘制的贝塞尔阶数列表,可按需扩展 const vector<int> bessel_orders = {0, 1, 2, 3}; const unsigned int curve_count = bessel_orders.size(); const unsigned int r = nresolution - 1; // 创建多通道绘图数据,通道数与待绘制曲线数量一致 CImg<double> values(1, nresolution, 1, curve_count, 0); // 为每条曲线生成采样数据 for (unsigned int curve_idx = 0; curve_idx < curve_count; ++curve_idx) { int current_order = bessel_orders[curve_idx]; for (int i1 = 0; i1 < resolution; ++i1) { double xtime = x0 + i1*(x1 - x0) / r; values(0, i1, 0, curve_idx) = boost::math::cyl_bessel_j<int, double>(current_order, xtime); } } // 生成每条曲线对应的图例标签 vector<string> label_strs; for (int order : bessel_orders) { label_strs.push_back("Order " + to_string(order)); } // 转换为CImg接口要求的字符串指针格式 vector<const char*> labels; for (auto& str : label_strs) { labels.push_back(str.c_str()); } // 调用绘图接口,自动适配坐标轴、配色与图例 values.display_graph(plot_title, plot_type, vertex_type, "X Axis", x0, x1, "Y Axis", labels.data()); }
额外说明
- CImg会自动根据通道数量分配高区分度的曲线配色,无需手动指定颜色
- 坐标轴Y轴范围会自动适配所有曲线的最大值、最小值,不需要手动计算边界
- 如果不需要显示图例,直接省略最后传入的
labels.data()参数即可
内容的提问来源于stack exchange,提问作者Protoss_Sine
相关产品推荐
相关产品推荐

