draw points using matplotlib.pyplot [[x1,y1],[x2,y2]]

Viewed 78808

I want to draw graph using a list of (x,y) pairs instead of using two lists, one of X's and one of Y's. Something like this:

a = [[1,2],[3,3],[4,4],[5,2]]
plt.plot(a, 'ro')

Rather than:

plt.plot([1,3,4,5], [2,3,4,2])

Suggestions?

4 Answers

You can do something like this:

a=[[1,2],[3,3],[4,4],[5,2]]
plt.plot(*zip(*a))

Unfortunately, you can no longer pass 'ro'. You must pass marker and line style values as keyword parameters:

a=[[1,2],[3,3],[4,4],[5,2]]
plt.plot(*zip(*a), marker='o', color='r', ls='')

The trick I used is unpacking argument lists.

Write a helper function.

Here is a longish version, but I am sure there is a trick to compress it.

>>> def helper(lst):
    lst1, lst2 = [], []
    for el in lst:
        lst1.append(el[0])
        lst2.append(el[1])
    return lst1, lst2

>>> 
>>> helper([[1,2],[3,4],[5,6]])
([1, 3, 5], [2, 4, 6])
>>> 

Also add this helper:

def myplot(func, lst, flag):
    return func(helper(lst), flag)

And call it like so:

myplot(plt.plot, [[1,2],[3,4],[5,6]], 'ro')

Alternatively you could add a function to an already instantiated object.

Related