Reputation: 903
i want to plot a consumption of electricty every 30 minutes over 2 month my code is working my problem is in xlabel i don't want to have range(1,2....48*58) but i want to have some thing like that between 1 and 48*30 give a nme of january between the secon 48*28 giving the name of february etc...
plt.xticks(rotation=70)
mask3 = (train['date'] >= '2008-01-01') & (train['date'] <= '2008-02-27')
week = train.loc[mask3]
plt.plot(range(48*58),week.LoadNette)
plt.ylabel("Electricy consumption")
plt.xlabel("Month")
plt.title('Electricity consumption / week')
plt.show()
Upvotes: 0
Views: 980
Reputation: 96
By searching «python matplotlib use dates as xlabel» on a search engine, you can find an example of what you want in the Matplotlib documentation : https://matplotlib.org/examples/api/date_demo.html.
This example supposes your xdata is dates however, which is not the case right now. You would need to create a list of dates and use that instead of your range(48*58) list, like this :
import pandas
xdata = pandas.date_range(
pandas.to_datetime("2008-01-01"),
pandas.to_datetime("2008-02-27 23:30:00"),
freq=pandas.to_timedelta(30,unit="m")).tolist()
This creates a list of datetimes from your start time to your end time at a frequency of 30 minutes.
After that, you'll need to use the example in the link above. Here it is reproduced and tweaked a bit to your needs, but you'll need to play around with it to set it properly. You can find many more examples of using dates in matplotlib now that you'll be using a date list as input for your plot.
import datetime
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.cbook as cbook
# define locators for every month and every day
months = mdates.MonthLocator() # every month
days = mdates.DayLocator() # every day
monthsFmt = mdates.DateFormatter('%m')
# create the plot and plot your data
fig, ax = plt.subplots()
ax.plot(xdata, week.LoadNette)
# format the x ticks to have a major tick every month and a minor every day
ax.xaxis.set_major_locator(months)
ax.xaxis.set_major_formatter(monthsFmt)
ax.xaxis.set_minor_locator(days)
# format the xlabel to only show the month
ax.format_xdata = mdates.DateFormatter('%m')
# rotates and right aligns the x labels, and moves the bottom of the
# axes up to make room for them
fig.autofmt_xdate()
plt.show()
Using dates in Matplotlib can be intimidating, but it's better in the long run than just hacking the labels you want this specific time.
Upvotes: 1