QCustomPlot Discussion and Comments

Plot very simple math functionReturn to overview

Hello,
I have a qcustomplot and I need it to draw very simply polynomial equations (such as f(x) = x^3 -2x^2 + 4). From the tutorial I was able to get this code:

QVector<double> x(101), y(101);
  for (int i=0; i<101; ++i) {
    x[i] = i/static_cast<double>(50) - 1; //instead of 50.0 I have a static cast but it's the same
    y[i] = poly.evaluate(x[i]); //function written by my own, it works
  }

  // create graph and assign data to it:
  ui->customPlot->addGraph();
  ui->customPlot->graph(0)->setPen(QPen(Qt::red));
  ui->customPlot->graph(0)->setData(x, y);

  // set axes ranges, so we see all data:
  ui->customPlot->xAxis->setRange(-1, 1);
  ui->customPlot->yAxis->setRange(-1, 1);
  ui->customPlot->replot();

This code works as expected! I have a problem by the way. If I want a bigger range I change this code:

  ui->customPlot->xAxis->setRange(-3, 3); //it was -1, 1 before
  ui->customPlot->yAxis->setRange(-3, 3); //it was -1, 1 before

If I change ONLY the range the function is still correctly plotted but it is still shown in the -1, 1 range! I think that I have to change somehow the x and y. Any help?

When I set the range to -3, 3 I get this plot for f(x) = -3x^2 -> https://image.prntscr.com/image/ruEuNUQCQwaZ7Kb7tBs2Ng.png (image)

Should I change the x code?
Note that poly.evaluate(x) is nothing particular, it just evaluates the polyn on the point x. So if poly is x^2, calling " poly.evaluate(x) " or 1*x*x has no difference.

pretty sure your for loop starts at -1 and ends at 1. this would of course lead to zeros outside of the range.

Try something like this.

Variables x_low, x_high and no_points can be controlled by adding suitable input widgets to the form.

void MainWindow::plot()
{
    double x_low = -3.0;
    double x_high = 3.0;

    double x_i = x_low;

    int no_points = 100;

    double dx = (x_high - x_low)/no_points;

    QVector<double> x, y;

    for (int i = 0; i < no_points; ++i)
    {
        x_i = x_low + i*dx;

        x.push_back( x_i );
        y.push_back( x_i*x_i*x_i - 2*x_i*x_i + 4);
    }

    // create graph and assign data to it:
    ui->customPlot->addGraph();
    ui->customPlot->graph(0)->setPen(QPen(Qt::red));
    ui->customPlot->graph(0)->setData(x, y);

    // set axes ranges, so we see all data:
    ui->customPlot->rescaleAxes();
    ui->customPlot->replot();
}