Search code examples
regressiongnuplot

When using Gnuplot, how can the equation of a line be printed in the line title?


I have used Gnuplot to plot my data, along with a linear regression line. Currently, the 'title' of this line, which has its equation calculated by Gnuplot, is just "f(x)". However, I would like the title to be the equation of the regression line, e.g. "y=mx+c".

I can do this manually by reading off 'm' and 'c' from the plotting info output, then re-plot with the new title. I would like this process to be automated, and was wondering if this can be done, and how to go about doing it.


Solution

  • With a data file Data.csv:

    0   0.00000
    1   1.00000
    2   1.41421
    3   1.73205
    4   2.00000
    5   2.23607
    

    you can do a linear fitting with:

    f(x) = a*x + b
    
    fit f(x) 'Data.csv' u 1:2 via a, b
    

    You can use what I think is called a macro in gnuplot to set the title in the legend of you identified function f(x) with

    title_f(a,b) = sprintf('f(x) = %.2fx + %.2f', a, b)
    

    Now in order to plot the data with the regression function f(x) simply do:

    plot "Data.csv" u 1:2 w l, f(x) t title_f(a,b)
    

    You should end up with this plot:

    enter image description here