Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I plot list of tuples in Python?

I have the following data set. I would like to use Python or Gnuplot to plot the data. The tuples are of the form (x, y). The Y-axis should be a log axis, that is, log(y). A scatter plot or line plot would be ideal.

How can this be done?

 [(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),   (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),   (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)] 
like image 673
olliepower Avatar asked Aug 27 '13 06:08

olliepower


People also ask

How do you use a list of tuples in Python?

List and Tuple are built-in container types defined in Python. Objects of both these types can store different other objects that are accessible by index. List as well as tuple is a sequence data type, just as string. List as well as tuple can store objects which need not be of same type.

Can you have a list of tuples in Python?

We can create a list of tuples i.e. the elements of the tuple can be enclosed in a list and thus will follow the characteristics in a similar manner as of a Python list. Since, Python Tuples utilize less amount of space, creating a list of tuples would be more useful in every aspect.


1 Answers

If I get your question correctly, you could do something like this.

>>> import matplotlib.pyplot as plt >>> testList =[(0, 6.0705199999997801e-08), (1, 2.1015700100300739e-08),   (2, 7.6280656623374823e-09), (3, 5.7348209304555086e-09),   (4, 3.6812203579604238e-09), (5, 4.1572516753310418e-09)] >>> from math import log >>> testList2 = [(elem1, log(elem2)) for elem1, elem2 in testList] >>> testList2 [(0, -16.617236475334405), (1, -17.67799605473062), (2, -18.691431541177973), (3, -18.9767093108359), (4, -19.420021520728017), (5, -19.298411635970396)] >>> zip(*testList2) [(0, 1, 2, 3, 4, 5), (-16.617236475334405, -17.67799605473062, -18.691431541177973, -18.9767093108359, -19.420021520728017, -19.298411635970396)] >>> plt.scatter(*zip(*testList2)) >>> plt.show() 

which would give you something like

enter image description here

Or as a line plot,

>>> plt.plot(*zip(*testList2)) >>> plt.show() 

enter image description here

EDIT - If you want to add a title and labels for the axis, you could do something like

>>> plt.scatter(*zip(*testList2)) >>> plt.title('Random Figure') >>> plt.xlabel('X-Axis') >>> plt.ylabel('Y-Axis') >>> plt.show() 

which would give you

enter image description here

like image 55
Sukrit Kalra Avatar answered Oct 02 '22 19:10

Sukrit Kalra