Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I plot a list of tuples with matplotlib?

I have a list of tuples with the tuples being (minTemp, averageTemp, maxTemp). I would like to plot a line graph of each of these elements in the tuple, on the same matplotlib figure.

How can this be done?

like image 600
Sam Avatar asked Dec 28 '14 18:12

Sam


People also ask

What does %Matplotlib do in Python?

Matplotlib is a cross-platform, data visualization and graphical plotting library for Python and its numerical extension NumPy. As such, it offers a viable open source alternative to MATLAB. Developers can also use matplotlib's APIs (Application Programming Interfaces) to embed plots in GUI applications.

Is PLT show () necessary?

Plotting from an IPython shell Some changes (such as modifying properties of lines that are already drawn) will not draw automatically: to force an update, use plt. draw() . Using plt. show() in Matplotlib mode is not required.


1 Answers

To get the array of the min, average and max temperature respectively, the zip functionis good as you can see here .

from pylab import plot, title, xlabel, ylabel, savefig, legend, array

values = [(3, 4, 5), (7, 8, 9), (2, 3, 4)]
days = array([24, 25, 26])

for temp in zip(*values):
    plot(days, array(temp))
title('Temperature at december')
xlabel('Days of december')
ylabel('Temperature')
legend(['min', 'avg', 'max'], loc='lower center')
savefig("temperature_at_christmas.pdf")

enter image description here

You can import these functions from numpy and matplotlib modules as well, and you can alter the layout (the color in the example) as follows:

from matplotlib.pyplot import plot, title, xlabel, ylabel, savefig, legend
from numpy import array

values = [(3, 4, 5), (5, 8, 9), (2, 3, 5), (3, 5, 6)]
days = array([24, 25, 26, 27])

min_temp, avg_temp, max_temp = zip(*values)
temperature_with_colors_and_labels = (
    (min_temp, 'green', 'min'),
    (avg_temp, 'grey', 'avg'),
    (max_temp, 'orange', 'max'),
)

for temp, color, label in temperature_with_colors_and_labels:
    plot(days, array(temp), color=color, label=label)
title('Temperature at december (last decade)')
xlabel('Days of december')
ylabel('Temperature (Celsius)')
legend()
savefig("temperature_at_christmas.png")

enter image description here

You can find the keyword arguments of the plot function on the matplotlib documentation or in the docstring of the function.

like image 192