# Sort the data to plot a circle

Here I have a data which I would to plot with line using Gnuplot. Using the code

``````pl 'Sphere_ISOTEST_data.txt' w p
``````

I get below figure

but, using

``````pl 'Sphere_ISOTEST_data.txt' w l
``````

I get the following:

Can anyone suggest as to how to sort the data such that I can plot `w l` and get only the circumference of the circle.

• And to complete the circle with @steeldriver's sorting, add the first point to the end of the data, e.g. filter the output of `sort` through `sed`: `sed '1h; \$G'`
– Thor
Commented Apr 29, 2021 at 15:01

This could be solved by converting the Cartesian coordinates into polar coordinates and sorting by the angle.

We can compute the angle as `atan2(y,x)`.

We may sort the original data using this computed number by applying a Schwartzian transform where the angle is used as the temporary sorting key:

``````awk -v OFS='\t' '{ print atan2(\$2,\$1), \$0 }' Sphere_ISOTEST_data.txt |
LC_ALL=C sort -g | cut -f 2-  >sorted.txt
``````

The `awk` program computes the `atan2()` value from the values in the file and prepends the original lines with this value for each line, using a tab character as delimiter. The `sort` utility then sorts the data and `cut` is used to remove the temporary sorting key.

Note that I'm using `sort -g`, which is non-standard. The `-g` option, when implemented, usually enables a "general numeric sort", which we will need to use as some of the `atan2()` values will be in scientific notation due to being very small. We also need to use the POSIX locale ("`C`") for `sort` to read and sort the numbers correctly. We could obviously work around this by modifying the output format of the `atan2()` values as we print them, but this at least shows the general idea.

The result is written to `sorted.txt`.

``````GNUTERM=png gnuplot -e 'set size square; pl "sorted.txt" w l' >sorted.png
``````