9

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.

JPK
  • 143
  • 1
  • 1
  • 7

2 Answers2

25

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

Woltan
  • 13,723
  • 15
  • 78
  • 104
1

From Correlation coefficient on gnuplot :

Another, perhaps slightly shorter way than Woltan's of doing the same thing may be:

# This command will analyze your data and set STATS_* variables. See help stats
stats Data.csv
f(x) = STATS_slope * x + STATS_intercept
plot f(x) title sprintf("y=%.2fx+%.2f", STATS_slope, STATS_intercept)
hdl
  • 1,028
  • 1
  • 9
  • 23
  • Just an FYI, the `stats` command cannot analyze your data when in `timedata mode, via the `xdata time`. – slm Jun 15 '19 at 13:39