Color mapping of data on a date vs time plot

為{幸葍}努か 提交于 2019-12-11 06:37:37

问题


I am trying to plot 3 variables x,y,z on a 2d plot, with x (date) on the x axis, y (time) on the y axis and z (temperature) mapped with a colorscale. I have the three variables available within a pandas Dataframe and created an extra column with the datenumber so that matplotlib can work with it.

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

data=pd.DataFrame() 
data['datenum']=mdates.date2num(data['Date'])

Example:

            Date Time     Tgrad   datenum
0     2016-08-01   00 -0.841203  736177.0
1     2016-08-01   01 -0.629176  736177.0
2     2016-08-01   02 -0.623608  736177.0
3     2016-08-01   03 -0.615145  736177.0
4     2016-08-01   04 -0.726949  736177.0
5     2016-08-01   05 -0.788864  736177.0
6     2016-08-01   06 -0.794655  736177.0
7     2016-08-01   07 -0.775724  736177.0
8     2016-08-01   08 -0.677951  736177.0

I have been trying to follow this suggestions:

matplotlib 2D plot from x,y,z values Dates in the xaxis for a matplotlib plot with imshow

But have not been successful due to the wrong shape of my input data I think. I have tried something like this:

fig, ax = plt.subplots()
ax.imshow(data['Tgrad'], extent = [min(data['datenum']), max(data['datenum']),min(data['Time']), max(data['Time'])], cmap="autumn", aspect = "auto")
ax.xaxis_date()

But get a ValueError:

ValueError: setting an array element with a sequence

Is it necessary to have the data as numpy array or any other type? And how can I map the data once I have it in a different format?

Thanks you for helping. Vroni


回答1:


imshow requires a 2d array as input. You'll need to reformat your data into a 2d array: Date x Time with Tgrad as your values. Pandas makes this fairly easy with pivot. It does require that you have nicely spaced data points, i.e., a grid-like data set (same Time values for each Date). The post you linked would be useful if data points were not neatly scattered in 2d space. Also, there's no need to convert to a numpy array as matplotlib can handle dataframes.

C = data.pivot(index='Time', columns='Date', values='Tgrad')

fig, ax = plt.subplots()
ax.imshow(C)


来源:https://stackoverflow.com/questions/53770530/color-mapping-of-data-on-a-date-vs-time-plot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!