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

Asked

Viewed 1,078 times

0

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

http://gnuplot.respawned.com/

I am trying to use gnuplot python. Assuming it would be similar to the online resource, I put "#" on 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 distinct 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 character " t") or string into two new lists(x and y), with my data separate? Is there any way I can use gnuplot python without having to do this, as occurs in gnuplot online?

1 answer

2


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

The first step is to break down the elements from the ' t''. For this, just use split: this function splits a string into a list of strings separated by the character or substring passed to it. We can use a list comprehension to apply the operation to all strings in the list in one 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 quite in the format we want. To turn our list into two distinct lists x and y, we can use the zip. He 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 have now x and y more or less as we wanted, but I imagine you want the value in the form of float or int, and not as strings (including whitespace, in the case of y). Again, list understandings can give a quick solution:

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 now here’s the thing:
  • a list, in which:
  • for each element valor of x, one of the elements of the new list corresponds to float(valor)
  • It works well. Thank you!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.