I want to add a trendline to my graph in Qt.
How to plot a trendline on a line graph?
Here's how to compute a trendline mathematically:
Slope:
Offset:
Trendline formula:
where
a is slope
x is the horizontal axis value
b is the Y-intercept
Normally you have sccattered data that makes up your graph. No matter if you use QtWidget or QML you can follow these steps.
First, find the average of the x values and the average of y values.
Next, find the distance between each x value and the average of the x values, and the distance between each y value and the average of the y values.
Then multiplying (x(i) - X(i)) by (y(i) - Y(i))
, and multiplying (x(i) - X(i))
by itself.
Get the sum of first formula ((x(i) - X(i)) by (y(i) - Y(i))
) and sum of second formula ( (x(i) - X(i))
)
Find the slop a by dividing first formula sum by second formula sum.
Get the average value of x and y and find b value using trendline formula : y = ax + b so b = y - ax
Then you have everything you want to apply your trendline equation
Using your equation, you could now draw your line trend on your QCustomPLot using two point:
QCPItemStraightLine *trendLine = new QCPItemStraightLine(customPlot);
trendLine->point1->setCoords(x, y); // location of point 1 in plot coordinate
trendLine->point2->setCoords(xx, yy); // location of point 2 in plot coordinate