Charly Roch
Charly Roch

Reputation: 368

Gnuplot - Use a 3rd non integer parameters in a plot

I want to make a plot from a csv file:

02/15/2016 09:32:58,LG.04,4747.0
02/15/2016 09:33:08,LG.03,2899.0
02/15/2016 09:33:18,LG.01,5894.0
02/15/2016 09:33:28,LG.04,6043.0

Using the column 1 which is the date, the 3rd is the value that I want to compare. This give me only one plot.

  reset
    date = system("date +%m-%d-%Y")
    set datafile separator ","
    set timefmt '%m/%d/%Y %H:%M:%S'
    set xdata time
    set format x "%m/%d/%Y\n%H:%M:%S"
    #
    plot '/home/'.system("echo $USER").'/Desktop/test.csv' u 1:3:2 w lp
    pause 200

I am wondering how to get many lines using the second column, and define the title of the different columns (using the csv value).

Upvotes: 2

Views: 260

Answers (1)

Matthew
Matthew

Reputation: 7590

To do this you will need to use an outside program to filter and reorganize the data. I'll demonstrate this using python3.

We need two python programs. The first, getnames.py, will get us the list of unique values in column 2:

data = open("test.csv","r").readlines()
names = [x.split(",")[1] for x in data]
print(" ".join(sorted(set(names))))

The second, filternames.py, will get us the lines in the data file corresponding to each unique value in column 2:

from sys import argv

nme = argv[1]

data = open("test.csv","r").readlines()
for x in data:
    if x.split(",")[1] == nme:
        print(x.strip())

Then, in gnuplot, we can call into these programs to process the data.

set datafile separator ","
set timefmt '%m/%d/%Y %H:%M:%S'
set xdata time
set format x "%m/%d/%Y\n%H:%M:%S"
names = system("getnames.py")
plot for [n in names] sprintf("< filternames.py %s",n) u 1:3 with linespoints t n

The first system call will get a string containing space separated unique values for this second column ("LG.01 LG.03 LG.04").

The plot command runs over each one of these values, and calls the filtering program to return only the lines corresponding to that value. The output of the filtering program is read directly by using the redirection operator.

enter image description here

Here, I moved the key to the left to keep the data off from it with set key left.

We can do the same thing using standard linux commands, if available. Instead of using the getnames.py program, we can do

names = system("awk -F, '{print $2}' test.csv | sort | uniq | tr '\n' ' '")

using awk to get the second column values, uniq to get only the unique values (which requires the values to be sorted with sort), and tr to replace newlines with spaces (returning the values as one space separated list).

Instead of using filternames.py, we can do

plot for [n in names] sprintf("< awk -F, '($2=="%s"){print $0}' test.csv",n) u 1:3 with linespoints t n

using awk to get only the lines with the desired second column value.

Upvotes: 1

Related Questions