2

I plot a CSV file in scatter-plot with connecting lines with gnuplot using the following command:

set style line 1 lc rgb '#0060ad' lt 1 lw 1 pt 7 pi -1 ps 1
set pointintervalbox 1.25

plot "values.csv" using 1:2 with lp ls 1 

It looks great, but what I get is an opened polygon because gnuplot doesn't draw the line connecting the first point and the last.

How do I get gnuplot to connect the first and last points so I get a closed polygon?

3
  • 1
    See this answer, and this on SO. Commented Oct 5, 2015 at 19:24
  • @vagoberto the linked answers are no solutions to this question, since there the first datapoint is already added, at the end which is apparently not the case here, otherwise OP's polygon would not be open. Commented Apr 21, 2023 at 18:32
  • @theozh I think that's the reason I didn't post it as an answer 8 years ago :) Commented Apr 25, 2023 at 5:05

2 Answers 2

2

The easiest way to do this is as suggested in the comments by modifying your data file. However, if you want to get fancy you can do some awk on-the-fly preprocessing to append the first data point to the end of the file.

Consider the following data file:

# Some comment for the sake of generality
0 0
1 1
2 1
2 0

Which looks like this without any processing (e.g., plot "data" w l):

enter image description here

We remove comments and add the first line to the end of the file:

datafile = "< grep -v '#' data | awk '{if(NR==1) {i += 1; temp = $0; print \
$0;} else {i += 1; print $0;}} END {print temp}'"

plot datafile w l

enter image description here

Sign up to request clarification or add additional context in comments.

Comments

0

Although you don't show data, but I can assume that you just have n-datapoints for a n-polygon. There is no reason why gnuplot should automatically close the curve to a polygon when plotting with lines or with linespoints. This would mean: adding the first datapoint again at the end. You have to do this yourself. You can do this via external tools like in Miguel's solution.

You can also do it with gnuplot only which would be platform-independent. Basically, you store the first and the last data point in x0,y0 and x1,y1, respectively and plot a closing line with vectors.

Data: SO32954260.dat

0 0
1 1
2 1
2 0

Script: (works with gnuplot>=4.4.0, March 2010)

### plot closed polygon
reset

FILE = "SO32954260.dat"

set offsets 1,1,1,1
set key noautotitle
set style line 1 lc rgb '#ff0000' lt 1 lw 2 pt 7 pi -1 ps 1

plot FILE u ($0==0?(x0=$1,y0=$2):0,x1=$1):(y1=$2) w lp ls 1, \
      '+' u (x0):(y0):(x1-x0):(y1-y0) every ::::0 w vec nohead ls 1
### end of script

Result:

enter image description here

Comments

Your Answer

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