Issue
I'm trying to plot multiple plots on the same figure using python. The graph should be linear, the x coordinates represent the time of the day, and the y coordinates match the values. Each plot matches a different date.
The data is stored inside a dictionary. The keys represent the dates, and the values hold 2 lists: the first matches the x coordinates, and the second matches the y coordinates. For example:
dict_data = {"4 April": [[datetime(1900, 1, 1, 22, 59), datetime(1900, 1, 1, 23, 1), datetime(1900, 1, 1, 23, 8), datetime(1900, 1, 1, 23, 50)], [405, 320, 300, 360]], "5 April": [[datetime(1900, 1, 1, 8, 10), datetime(1900, 1, 1, 9, 40), datetime(1900, 1, 1, 11, 8), datetime(1900, 1, 1, 11, 10)], [120, 20, 10, 0]]}
I found apost on stack overflow Plotting time in Python with Matplotlib. It was'nt helpful because the x-axis on the graph they created is in "datetime" type, while I use "datetime.time"datetime". (I don't want the x-axis to show the dates). Also, the graph they created is a scatter plot, while I need it to be linear.
This is what I tried:
def multiple_plots(dict_data):
"""
Method to plot multiple times in one figure.
It receives a dictionary with the representation of the data in the csv file.
Every key in the dictionary represent a different date that will have its own plot ont the graph.
"""
for date, coordinates in dict_data.items():
time_coordinates = coordinates[0]
# converting the x coordinates in the type datetime.time to int
x_coordinates = matplotlib.dates.date2num(time_coordinates)
val_coordinates = coordinates[1]
plt.plot(list(map(int, x_coordinates)), list(map(int, val_coordinates)), label=date)
plt.legend(loc='best')
plt.show()
Solution
This should just work without any fuss:
import matplotlib.pyplot as plt
import datetime
dict_data = {"4 April": [[datetime.datetime(1900, 1, 1, 22, 59), datetime.datetime(1900, 1, 1, 23, 1), datetime.datetime(1900, 1, 1, 23, 8), datetime.datetime(1900, 1, 1, 23, 50)], [405, 320, 300, 360]], "5 April": [[datetime.datetime(1900, 1, 1, 8, 10), datetime.datetime(1900, 1, 1, 9, 40), datetime.datetime(1900, 1, 1, 11, 8), datetime.datetime(1900, 1, 1, 11, 10)], [120, 20, 10, 0]]}
fig, ax = plt.subplots()
for k in dict_data:
ax.plot(dict_data[k][0], dict_data[k][1])
plt.show()
Obviously that looks a little cramped, but if you use concise converter:
plt.rcParams['date.converter'] = 'concise'
Answered By - Jody Klymak
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.