1

I have a list of (x,y) values that are in a list like [(x,y),(x,y),(x,y)....]. I feel like there is a solution in matplotlib, but I couldn't quite get there because of my formatting. I would like to plot it as a histogram or line plot. Any help is appreciated.

pioneer903
  • 171
  • 1
  • 1
  • 12

2 Answers2

7

You can quite easily convert a list of (x, y) tuples into a list of two tuples of x- and y- coordinates using the * ('splat') operator (see also this SO question):

>>> zip(*[(0, 0), (1, 1), (2, 4), (3, 9)])
[(0, 1, 2, 3), (0, 1, 4, 9)]

And then, you can use the * operator again to unpack those arguments into plt.plot

>>> plt.plot(*zip(*[(0, 0), (1, 1), (2, 4), (3, 9)]))

or even plt.bar

>>> plt.bar(*zip(*[(0, 0), (1, 1), (2, 4), (3, 9)]))
Community
  • 1
  • 1
Adam Obeng
  • 1,512
  • 10
  • 13
2

Perhaps you could try something like this (also see):

import numpy as np:
xs=[]; ys=[]
for x,y in xy_list:
  xs.append(x)
  ys.append(y)
xs=np.asarray(xs)
ys=np.asarray(ys)
plot(xs,ys,'ro')

Maybe not the most elegant solution, but it should work. Cheers, Trond

Community
  • 1
  • 1
Trond Kristiansen
  • 2,379
  • 23
  • 48