Plotting a function directly from a text file

后端 未结 3 838
遥遥无期
遥遥无期 2020-12-18 02:05

Is there a way to plot a function based on values from a text file?

I know how to define a function in gnuplot and then plot it but that is not what I need. I have a

3条回答
  •  半阙折子戏
    2020-12-18 02:18

    This question (gnuplot store one number from data file into variable) had some hints for me in the first answer.

    In my case I have a file which contains parameters for a parabola. I have saved the parameters in gnuplot variables. Then I plot the function containing the parameter variables for each timestep.

    #!/usr/bin/gnuplot
    
    datafile = "parabola.txt"
    
    set terminal pngcairo size 1000,500
    set xrange [-100:100]
    set yrange [-100:100]
    titletext(timepar, apar, cpar) = sprintf("In timestep %d we have parameter a = %f, parameter c = %f", timepar, apar, cpar)
    
    do for [step=1:400] {
      set output sprintf("parabola%04d.png", step)
    
      # read parameters from file, where the first line is the header, thus the +1
      a=system("awk '{ if (NR == " . step . "+1) printf \"%f\", $1}' " . datafile)
      c=system("awk '{ if (NR == " . step . "+1) printf \"%f\", $2}' " . datafile)
    
      # convert parameters to numeric format
      a=a+0.
      c=c+0.
    
      set title titletext(step, a, c)
    
      plot   c+a*x**2
    }
    

    This gives a series of png files called parabola0001.png, parabola0002.png, parabola0003.png, …, each showing a parabola with the parameters read from the file called parabola.txt. The title contains the parameters of the given time step.

    For understanding the gnuplot system() function you have to know that:

    • stuff inside double quotes is not parsed by gnuplot
    • the dot is for concatenating strings in gnuplot
    • the double quotes for the awk printf command have to be escaped, to hide them from gnuplot parser

    To test this gnuplot script, save it into a file with an arbitrary name, e.g. parabolaplot.gplot and make it executable (chmad a+x parabolaplot.gplot). The parabola.txt file can be created with

    awk 'BEGIN {for (i=1; i<=1000; i++) printf "%f\t%f\n", i/200, i/100}' > parabola.txt

提交回复
热议问题