Reputation: 422
Here's how my data looks like:
[{'date': '09/03/2021', 'time': '12:30', 'value': '12.9'}, ...]
I can plot data for a given day or for all days. When I plot all the days, I use the 'date' for the x-axis and the y-axis is the sum of all values for that day.
In my previous plots, I was doing it by the hour, so the x-axis was nicely spaced between. When I try to plot when every entry is by the minute, this happens:
plt.plot(xy_val[0], xy_val[1], '-r', label='Consumo')
Besides taking a long time to show the image, doesn't look very nice, Ahah.
I read somewhere that matplotlib likes the datetime format, so I've modified the code a little.
for i in range(0, len(xy_val[0])):
temp = datetime.datetime.strptime(xy_val[0][i], '%H:%M')
xy_val[0][i] = temp
plt.plot(xy_val[0], xy_val[1], '-r', label='Consumo')
And I get this:
I guess the first part of the string corresponds to the year 01-01-1990 and the last one is the hour. For when I plot a single day, I would like only to write the hour, so that they can be nicely spaced. For when I plot for multiple days, I would like to use the ('%Y/%M/%D')
format and if there's too many, the ('%M/%Y')
or even ('%Y')
if I decide to go nuts. matplotlib seems very smart, so I think if I give the correct format, it can do very easily for me.
Thank you for reading this and sorry if this question is too dumb. Have a nice day. :)
Upvotes: 3
Views: 3214
Reputation: 41487
You can use matplotlib.dates.DateFormatter
to set the axis date format.
Using this sample data:
from datetime import datetime
xy_val = [{'date':'09/03/2020','time':'12:30','value':'12.9'},{'date':'09/14/2020','time':'2:40','value':'32.9'},{'date':'10/04/2020','time':'8:50','value':'22.9'},{'date':'01/06/2021','time':'15:50','value':'21.0'},{'date':'03/06/2021','time':'18:50','value':'52.9'}]
x = [datetime.strptime(val['date'] + val['time'], '%m/%d/%Y%H:%M') for val in xy_val]
y = [float(val['value']) for val in xy_val]
Define fmt
with your desired format and apply it with set_major_formatter(fmt)
:
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
# define desired date format
fmt = mdates.DateFormatter('%Y')
fig, ax = plt.subplots()
ax.plot(x, y)
# apply fmt to axis
ax.xaxis.set_major_formatter(fmt)
fig.autofmt_xdate()
Output of various formats:
Upvotes: 2
Reputation: 21
You can plot by the hour axis by getting the hours into a list as below and plotting against those. The same can be done for the days.
from matplotlib import pyplot as plt import datetime
xy_val= [{'date': '09/03/2021', 'time': '12:30', 'value': '12.9'}, {'date': '09/03/2021', 'time': '13:30', 'value': '12.9'}]
list_of_hours = [] for i in range(0, len(xy_val)):
list_of_hours.append(xy_val[i]["time"].split(":")[0])
list_of_values= [] for i in range(0, len(xy_val)):
list_of_values.append(xy_val[i]["value"].split(":")[0])
plt.plot(list_of_hours, list_of_values, '-r', label='Consumo') plt.show()
Upvotes: 1