2017-08-09 172 views
2

我有一些数据,看起来像这样:如何在x-y轴上使用日期和时间绘制轮廓图?

#date  time  temp press rh 
09/10/2011 07:50  11.4 798.1 14.1 
09/10/2011 08:00  11.9 798.3 13.6 
... 
09/10/2011 11:30  FALSE FALSE FALSE 
09/10/2011 11:40  25.4 798.3 11.2 
09/10/2011 11:50  23.2 799.1 11.2 
..... 

我想这样做“临时”的等高线图与y轴在x轴上的“时间”和“日期”。

我试过用大熊猫来处理日期和NaN值更好。

data=np.genfromtxt("dataFile.txt", comments="#", dtype='str') 

header_names=['date', 'time', 'temp', 'press', 'rh'] 
df = pd.DataFrame(data, dtype=None, columns=header_names) 
df['date']=pd.to_datetime(df['date'], format='%d/%m/%Y').dt.date 
df.time=pd.to_datetime(df.time, format='%H:%M').dt.time 
df.temp = pd.to_numeric(df.temp, errors='coerse') 
.... 

dfMesh=df.pivot('date', 'time', 'temp') 
X=dfMesh.columns.values 
Y=dfMesh.index.values 
Z=dfMesh.values 

x,y=np.meshgrid(X, Y) 
plt.contourf(x, y, Z) 

,但我得到了以下错误:

Traceback (most recent call last): File "./contourPlot_pandas.py", line 33, in x,y=np.meshgrid(X, Y) File "/Users/marybau/anaconda/lib/python3.6/site-packages/numpy/lib/function_base.py", line 4533, in meshgrid return [x * mult_fact for x in output] File "/Users/marybau/anaconda/lib/python3.6/site-packages/numpy/lib/function_base.py", line 4533, in return [x * mult_fact for x in output] TypeError: unsupported operand type(s) for *: 'datetime.time' and 'int

'

我自己也尝试其他不同的方式来做到这一点,而无需使用熊猫,但我最终因类似的问题date-time格式或NaN。有什么建议么?谢谢!

回答

1

matplotlib contour需要将X和Y值转换为浮点数,这取决于我在哪里得到错误消息。等高线绘图非常复杂,重新绘制日期时间以便与现有函数良好地绘制在一起可能比扩展contour更容易。

将日期和时间值转换为将正确分隔的数字;例如,日期为Julian日期整数,时间为自午夜以来的分钟数。与制造假数据,然后开始重新格式化:

import matplotlib.pyplot as plt 
import pandas as pd 
from math import pi, sin 

ts = pd.date_range('1/1/2017 0:00', '1/24/2017 23:00', freq='H') # 24 * 24 long 
temp = map(lambda x: sin(2*pi*x/40), range(576)) 
# tiny testcase: sin(2*pi*x/12) or /24 provide horizontal contours: quite right. 


df = pd.DataFrame({'date':map(lambda x:int(x.to_julian_date()), ts), 
        'time':map(lambda x:x.time().hour*60 + x.time().minute, ts), 
        'temp':temp}) 

dfMesh = df.pivot('time','date','temp') 

fig, ax = plt.subplots() 

conts = ax.contour(dfMesh.columns.values, dfMesh.index.values, dfMesh.values) 
ax.set_xlabel('Julian day') 
ax.set_ylabel('Minutes since midnight') 

plt.show() 

enter image description here

,会为你的调查数据作为昼夜等高线图做。

为了使绘图标签更容易理解,您可以编辑现有的标签,或者更改标签放置的位置,并给新标签打上日期或时间字符串标签。但这些问题是SE在其他地方处理的问题,如缺少值的等值线绘图,插值等。