15

How do I plot a vector field, where the direction at each point (x, y) is given by tangent(alpha) = f(x, y)?

2 Answers 2

19

As far as I can tell, gnuplot can only plot vector fields when reading data from a file. Your file will have to have 4 columns, x, y, deltax and delta y, and gnuplot will then plot a vector from (x,y) to (x+deltax, y+deltay) for each line in the file:

plot "file.dat" using 1:2:3:4 with vectors head filled lt 2

If you are not insisting on using gnuplot, there are other tools that can to this better or at least easier. I personally use asymptote. There is an example of a vectorfield plotted in asymptote here.

14

It seems this question/answer is a bit old, and since I believe that gnuplot is changed a bit in the latest versions, probably the answer should be updated.

I found a nice and compact solution here, by thse: http://gnuplot.10905.n7.nabble.com/Vector-Fields-td3627.html

which I will report for convenience:

set xrange [-5:5]
set yrange [-5:5]
# only integer x-cordinates
set samples 11
# only integer y-cordinates
set isosamples 11
# we need data, so we use the special filename "++", which
# produces x,y-pairs
plot "++" using 1:2:1:(2.*$2) with vectors

Here, the original question was how to plot the vector field F(x,y) = <x, 2y>. The trick is in the plot "++", which is a special file name which allows to use functions in the using specifier.

So, as @Jan said in his answer, gnuplot needs 4 fields in the data file to plot a vector field, but here the fields are synthetic and produced with two functions.

An equivalent formulation using defined functions could be:

set xrange [-5:5]
set yrange [-5:5]
dx(x) = x
dy(x) = 2*x
plot "++" using 1:2:(dx($1)):(dy($2)) w vec

See help special-filenames for further details.

HIH

3
  • 1
    the equivalent formulation gives error: "x range is invalid" .
    – kiltek
    Jan 21, 2015 at 8:36
  • It works for me, are you sure you typed everything correctly?
    – AkiRoss
    Jan 21, 2015 at 10:30
  • 1
    @AkiRoss, please add set xrange [-5:5] set yrange [-5:5] to the equivalent formulation example. If someone uses the existing three lines of the example verbatim, they get an "x range is invalid" error. Thank you! Sep 20, 2015 at 9:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.