How to break a list into two separate lists to use in Gnuplot python?

0

A feature of online gnuplot allows you to place your data in two columns separated by space, and it understands how the "x" and "y" axes

link

I'm trying to use python gnuplot. Assuming it would be similar to the online feature, I put "#" in what was not given and tried to plot. However, I found only tutorial asking to separate the x-axis from the y-axis into two separate lists.

I have a list (which can also be in string format), as in the example below:

lista = ['59.99167\t-3180\r\n', '60.00000\t-3181\r\n']

string = 59.99167 -3180 60.00000 -3181

My questions are: how do I easily break my list (in the "\ t" character) or string in two new lists (x and y), with my data separated? Is there any way I can use gnuplot python without having to do this, as it does in gnuplot online?

    
asked by anonymous 17.06.2018 / 22:24

1 answer

1

I do not know the gnuplot, but it's not difficult to separate your list into two lists with x and y values in Python.

The first step is to break the elements from the '\ t'. For this, just use split : this function divides a string into a list of strings separated by the character or substring passed to it. We can use a list understanding to apply the operation to all the strings of the list in a single line:

lista = ['59.99167\t-3180\r\n', '60.00000\t-3181\r\n']
lista_split = [dado.split('\t') for dado in lista]
print(lista_split)
# [['59.99167', '-3180\r\n'], ['60.00000', '-3181\r\n']]

We now have a list of lists, but not well in the format we want. To turn our list into two separate lists x and y , we can use zip . It gives us two tuples, so if we really want lists just say:

x, y = zip(*lista_split)
x, y = list(x), list(y)
print(x)
# ['59.99167', '60.00000']
print(y)
# ['-3180\r\n', '-3181\r\n']

As you can see, we now have x and y more or less as we wanted, but I imagine you want the value as float or int , not as strings (including whitespace, case of y ). Once again, list comprehensions can provide a quick fix:

x = [float(valor) for valor in x]
print(x)  # [59.99167, 60.0]
y = [float(valor) for valor in y]
print(y)  # [-3180.0, -3181.0]

Translating:

  • x is now as follows:
  • a list, where:
  • For each element valor of x , one of the elements of the new list corresponds to float(valor)
18.06.2018 / 01:45