Jump to content

Datetime annoyances - python matplotlib

DominHoes
Go to solution Solved by DominHoes,
5 hours ago, Sauron said:

Then it's possible matplotlib doesn't recognize the datetime.date format. Try using matplotlib.dates, you may have better luck.

Found the solution.

By importing matplotlib.dates, i was able to access 'mdates.Dateformatter' and use it in plt current axes or plt.gca().

Spoiler

#format plot
title="Daily high and low temperatures, - 2014"
plt.title(title, fontsize=20)
plt.xlabel('', fontsize=8)
#ax.xaxis.set_major_formatter(myFmt)
#plt.xlim([datetime.date(2014,1,1), datetime.date(2014,12,22)])
fig.autofmt_xdate()
myFmt = mdates.DateFormatter('%Y-%b-%d')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.ylim(10, 120)

 

 

I'm back with more python problems!

I was trying to get date, high and low of a temperature from sitka weather in 2014.csv

The dates start from 2014-1-1 and end in 2014-12-22

Spoiler

#highs_lows.py
import csv
from datetime import datetime
from matplotlib import pyplot as plt

#get dates and high and low temperatures from file
filename = 'sitka_weather_2014.csv'
with open(filename) as f:
	reader = csv.reader(f)
	header_row = next(reader)
	
	#print(header_row)
	for index, column_header in enumerate(header_row):
		print(index, column_header)
		
	dates, highs , lows= [], [], []
	for row in reader:
		try:
			current_date = datetime.strptime(row[0], "%Y-%m-%d")
			high = int(row[1])
			low = int(row[3])
		except ValueError:
			print(current_date, 'missing data')
		else:
			dates.append(current_date)
			highs.append(high)
			lows.append(low)
			
	print(current_date)
	print(highs)

#plot data
fig = plt.figure(dpi=128, figsize=(10, 6))
#shading with alpha
plt.plot(dates, highs, c='red', alpha=0.5)
plt.plot(dates, lows, c='blue', alpha=0.5)
plt.fill_between(dates, highs, lows, facecolor='blue', alpha=0.1)

#format plot
title="Daily high and low temperatures, - 2014"
plt.title(title, fontsize=20)
plt.xlabel('', fontsize=8)
plt.xlim([datetime.date(2014-1-1), datetime.date(2014-12-22)])
fig.autofmt_xdate()
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.ylim(10, 120)

plt.show()

 

That code shows me the graph i attached below.

Problem is the ticks or step size of the date is by 2, i was trying to change it to day-month-year with autofmt_xdate but all i got was Year and month.

I suppose the code misinterpret the month and or the day in 2014-1-1 in weather_history-2014.csv.

I have tried xlim but cant really do it with datetime.date(2014,-1,-1) it shows me

 

plt.xlim([datetime.date(2014-1-1), datetime.date(2014-12-22)])
TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object

long story short, how to change 2014-01 to 01-January-2014?

 

Edit:

Solved by using the matplotlib.dates to format the x-labels

here is the code

myFmt = mdates.DateFormatter('%Y-%b-%d')
plt.gca().xaxis.set_major_formatter(myFmt)

The ticks or step size of the X might still be by 2, but for now im satisfied.

 

Edit:

add this to set x labels by month. MonthLocator for every month, YearLocator for every year

plt.gca().xaxis.set_major_locator(mdates.MonthLocator())

 

Figure_1.png

Link to comment
Share on other sites

Link to post
Share on other sites

You're calling the constructor for a datetime.date object incorrectly. The correct syntax is

datetime.data(2014,1,1)

the error you're getting is telling you that 2014-1-1 is being interpreted as a subtraction which only returns one integer while the constructor requires 3. The reason 2014,-1,-1 doesn't work is that you're using negative numbers for the day and month (-1) which is obviously unsupported.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

3 minutes ago, Sauron said:

You're calling the constructor for a datetime.date object incorrectly. The correct syntax is


datetime.data(2014,1,1)

 

tried it, still gives me

Traceback (most recent call last):
  File "highs_lows.py", line 43, in <module>
    plt.xlim([datetime.date(2014,1,1), datetime.date(2014,12,22)])
TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object

 

Link to comment
Share on other sites

Link to post
Share on other sites

53 minutes ago, DominHoes said:

tried it, still gives me


Traceback (most recent call last):
  File "highs_lows.py", line 43, in <module>
    plt.xlim([datetime.date(2014,1,1), datetime.date(2014,12,22)])
TypeError: descriptor 'date' for 'datetime.datetime' objects doesn't apply to a 'int' object

 

Then it's possible matplotlib doesn't recognize the datetime.date format. Try using matplotlib.dates, you may have better luck.

Don't ask to ask, just ask... please 🤨

sudo chmod -R 000 /*

Link to comment
Share on other sites

Link to post
Share on other sites

5 hours ago, Sauron said:

Then it's possible matplotlib doesn't recognize the datetime.date format. Try using matplotlib.dates, you may have better luck.

Found the solution.

By importing matplotlib.dates, i was able to access 'mdates.Dateformatter' and use it in plt current axes or plt.gca().

Spoiler

#format plot
title="Daily high and low temperatures, - 2014"
plt.title(title, fontsize=20)
plt.xlabel('', fontsize=8)
#ax.xaxis.set_major_formatter(myFmt)
#plt.xlim([datetime.date(2014,1,1), datetime.date(2014,12,22)])
fig.autofmt_xdate()
myFmt = mdates.DateFormatter('%Y-%b-%d')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.ylabel("Temperature (F)", fontsize=16)
plt.tick_params(axis='both', which='major', labelsize=16)
plt.ylim(10, 120)

 

 

Link to comment
Share on other sites

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×