Jump to content
Search In
  • More options...
Find results that contain...
Find results in...
DominHoes

Datetime annoyances - python matplotlib

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)

 

 

Recommended Posts

Posted · Original PosterOP

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 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.


...is there a question here? 🤔

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to post
Share on other sites
Posted · Original PosterOP
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 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.


...is there a question here? 🤔

sudo chmod -R 000 /*

What is scaling and how does it work? Asus PB287Q unboxing! Console alternatives :D Watch Netflix with Kodi on Arch Linux Sharing folders over the internet using SSH Beginner's Guide To LTT (by iamdarkyoshi)

Sauron'stm Product Scores:

Spoiler

Just a list of my personal scores for some products, in no particular order, with brief comments. I just got the idea to do them so they aren't many for now :)

Don't take these as complete reviews or final truths - they are just my personal impressions on products I may or may not have used, summed up in a couple of sentences and a rough score. All scores take into account the unit's price and time of release, heavily so, therefore don't expect absolute performance to be reflected here.

 

-Lenovo Thinkpad X220 - [8/10]

Spoiler

A durable and reliable machine that is relatively lightweight, has all the hardware it needs to never feel sluggish and has a great IPS matte screen. Downsides are mostly due to its age, most notably the screen resolution of 1366x768 and usb 2.0 ports.

 

-Apple Macbook (2015) - [Garbage -/10]

Spoiler

From my perspective, this product has no redeeming factors given its price and the competition. It is underpowered, overpriced, impractical due to its single port and is made redundant even by Apple's own iPad pro line.

 

-OnePlus X - [7/10]

Spoiler

A good phone for the price. It does everything I (and most people) need without being sluggish and has no particularly bad flaws. The lack of recent software updates and relatively barebones feature kit (most notably the lack of 5GHz wifi, biometric sensors and backlight for the capacitive buttons) prevent it from being exceptional.

 

-Microsoft Surface Book 2 - [Garbage - -/10]

Spoiler

Overpriced and rushed, offers nothing notable compared to the competition, doesn't come with an adequate charger despite the premium price. Worse than the Macbook for not even offering the small plus sides of having macOS. Buy a Razer Blade if you want high performance in a (relatively) light package.

 

-Intel Core i7 2600/k - [9/10]

Spoiler

Quite possibly Intel's best product launch ever. It had all the bleeding edge features of the time, it came with a very significant performance improvement over its predecessor and it had a soldered heatspreader, allowing for efficient cooling and great overclocking. Even the "locked" version could be overclocked through the multiplier within (quite reasonable) limits.

 

-Apple iPad Pro - [5/10]

Spoiler

A pretty good product, sunk by its price (plus the extra cost of the physical keyboard and the pencil). Buy it if you don't mind the Apple tax and are looking for a very light office machine with an excellent digitizer. Particularly good for rich students. Bad for cheap tinkerers like myself.

 

 

Link to post
Share on other sites
Posted · Original PosterOP · Best Answer
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 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


×