Simon
Simon

Reputation: 85

How to create heatmap from pandas dataframe with date and time axes?

I am trying to create heatmap from pandas dataframe like this

datetime
2008-12-31 21:15:00    0
2008-12-31 21:45:00    0
2008-12-31 22:15:00    0
2008-12-31 22:45:00    0
2008-12-31 23:15:00    0
2008-12-31 23:45:00    0
2009-01-01 00:15:00    0
2009-01-01 00:45:00    0
2009-01-01 01:15:00    0
2009-01-01 01:45:00    0
...
Freq: 30T, Name: GHI, dtype: int64

Dataframe can have hundred thousands rows. Then I am able to create 2d array and plot it:

array2d = pd.pivot(index=df.index.time, columns=df.index[:].date, values=df.values)
ax.pcolormesh(array2d,cmap='jet')

Array2d:

          2008-12-31  2009-01-01     ...      2009-12-30  2009-12-31
00:15:00         NaN         0.0     ...             0.0         0.0
00:45:00         NaN         0.0     ...             0.0         0.0
01:15:00         NaN         0.0     ...             0.0         0.0
01:45:00         NaN         0.0     ...             0.0         0.0
02:15:00         NaN         0.0     ...             0.0         0.0
02:45:00         NaN         0.0     ...             0.0         0.0
03:15:00         NaN         0.0     ...             0.0         0.0
03:45:00         NaN         0.0     ...             0.0         0.0
...
[48 rows x 366 columns]

My plot then looks like this: heatmap

But I would like to have on x and y axes dates and times from array2d rather than numbers. Thanks

Upvotes: 0

Views: 1053

Answers (1)

tda
tda

Reputation: 2133

Does adding:

ax.set_yticklabels(array2d.index)
ax.set_xticklabels(array2d.columns) # may require .values at the end

to your code work? You have not specified what the x and y tick labels are and hence matplotlib is using numerical values rather than the date/times you wish it to be. You may need to change number of x and y ticks here using ax.set_xticks().

Something like this has an equal affect but allows you to set the number of ticks as well as the labels:

plt.pcolor(array2d)
plt.yticks(np.arange(1, len(array2d.index), 10), arra2d.index)
plt.xticks(np.arange(1, len(array2d.columns), 10), array2d.columns)
plt.show()

Upvotes: 2

Related Questions