Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: How to add datetime to x-axis in pcolormesh

With matplotlib scatter or line plots I can assign the x-axis as an array of datetimes.

from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt

size = 10

# List of Dates
base = datetime.today()
date_list = [base - timedelta(weeks=x) for x in range(0, size)]

plt.figure(1)
a = np.random.random([size])
plt.plot(date_list,a)
plt.xticks(rotation=45)

enter image description here

I would like to make a pcolormesh plot with datetime as the x-axis, but get an error

This works, but not what I want...

b = np.random.random([size,size])
plt.figure(2)
c = np.arange(0,size)
plt.pcolormesh(c,c,b)

enter image description here

This throws and error...

plt.figure(3)
plt.pcolormesh(date_list,c,b)

If you can't feed pcolormesh with a datetime array, is there another way to format the x-axis as dates?

Update

The issue seems to have been resolved in an updated version of matplotlib. Adding datetimes to a pcolormesh xaxis now works (version 3.4.3)

from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt

size = 10

b = np.random.random([size, size])

# List of Dates
base = datetime.today()
date_list = [base - timedelta(hours=x) for x in range(0, size)]

c = np.arange(0,size)

plt.pcolormesh(date_list, c, b, shading='auto')
plt.xticks(rotation=45)

enter image description here

like image 910
blaylockbk Avatar asked Sep 03 '25 14:09

blaylockbk


1 Answers

Something like this:

from datetime import datetime, timedelta
import numpy as np
import matplotlib.pyplot as plt

size = 10

# List of Dates
base = datetime.now()
date_list = [base - timedelta(weeks=x) for x in range(0, size)]
date_list = [i.strftime("%Y %m %d") for i in date_list]

b = np.random.random([size,size])
plt.figure(2)
c = np.arange(0,size)
plt.pcolormesh(c,c,b)
plt.xticks(c, date_list, rotation='vertical')
plt.subplots_adjust(bottom=0.2)
plt.show()

enter image description here

like image 61
VlS Avatar answered Sep 05 '25 09:09

VlS