7

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?

erakitin
  • 11,437
  • 5
  • 44
  • 49
Sam
  • 1,052
  • 4
  • 13
  • 33

1 Answers1

9

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.

Community
  • 1
  • 1
  • Thanks! Do you know how to change the colours of the three lines? I can't find it in the documentation. – Sam Dec 28 '14 at 22:25
  • 1
    @Samuel There is a version now with given colors in the answer. Would you accept this answer if it is answers your question? – Arpad Horvath -- Слава Україні Dec 29 '14 at 12:52
  • Thank's to your answer, I understood that the canonical way to plot a list of tuples is like this: `XY=[(1,2), (3,4), (5,6)]; x_only, y_only = zip(*XY); plt.plot(x_only, y_only)` – gaborous Aug 08 '16 at 19:39
  • Perhaps not canonical, but the shortest way, I think. zip(*XY) works as if you would call zip with the elements of the XY lists as positional arguments, as follows: `zip((1,2), (3,4), (5,6))` Here is [the documentation of the zip command](https://docs.python.org/3/library/functions.html#zip). – Arpad Horvath -- Слава Україні Aug 11 '16 at 13:21