首页 > 解决方案 > 使用带有日期时间数据的 pcolor 和 pcolormesh 的着色选项 - 日期插值问题

问题描述

我有一个大型数据集,在不同时间有不同高度的温度。我希望使用 pcolormesh 将其绘制为热图。

当我这样做时,我会收到警告MatplotlibDeprecationWarning: shading='flat' when X and Y have the same dimensions as C is deprecated since 3.3. Either specify the corners of the quadrilaterals with X and Y, or pass shading='auto', 'nearest' or 'gouraud', or set rcParams['pcolor.shading']. This will become an error two minor releases later.

结果,我尝试传递选项shading='nearest'以确保保留所有数据(shading='flat'删除行和列)。这给了我一个错误的形式numpy.core._exceptions.UFuncTypeError: Cannot cast ufunc 'greater_equal' input 0 from dtype('<m8[ns]') to dtype('<m8') with casting rule 'same_kind'

在我看来,将四边形角的插值应用于日期数据存在问题(我可以看到这会很棘手),但我一直在寻找并且找不到一种方法来完成这项工作。我可以尝试将日期完全转换为秒并插入为整数,但我希望在轴刻度上具有其当前形式。

有简单的解决方案吗?TIA

复制错误的简单片段如下:

import matplotlib.pyplot as plt
import pandas as pd
data = [
        ['2018-12-26 00:00:00',0,5,10],
        ['2018-12-26 06:00:00',1,6,9 ],
        ['2018-12-26 12:00:00',2,7,8 ],
        ['2018-12-26 18:00:00',3,8,7 ],
        ['2018-12-27 00:00:00',4,9,6 ],
       ]
df = pd.DataFrame(data)
df.columns = ['date', 0, 10, 20]
df['date'] = pd.to_datetime(df['date'])
dates = df['date']
heights = df.iloc[:,1:].columns
temp = df.iloc[:,1:].transpose()
fig = plt.figure()
im = plt.pcolormesh(dates, heights, temp,
                      shading='nearest')

标签: pythondatetimematplotlibheatmap

解决方案


我建议使用Seaborn库来创建热图。

这是我使用您的示例数据的解决方案:

# Import packages
import seaborn 
import numpy as np
import matplotlib.pyplot as plt

# Create sample data
data = [
        ['2018-12-26 00:00:00',0,5,10],
        ['2018-12-26 06:00:00',1,6,9 ],
        ['2018-12-26 12:00:00',2,7,8 ],
        ['2018-12-26 18:00:00',3,8,7 ],
        ['2018-12-27 00:00:00',4,9,6 ],
       ]

# Load sample into dataframe
df = pd.DataFrame(data)
df.columns = ['date', 0, 10, 20]
temp = df.iloc[:,1:].transpose()

# Convert data to numpy array, AND flip the data (and later y tick labels) 
# so that the height is in increasing order from bottom to top in the heatmap
data2 = temp.to_numpy()
data2 = np.flip(data2, axis=0)

# Create empty figure
plt.figure(figsize=(15,5))

# Create heatmap (with customized colorscales, x/y ticks, line color, etc.)
seaborn.heatmap(data2, annot=True, linewidths=.5, linecolor='k', square=False, 
                     xticklabels=df.date, yticklabels=np.flip(temp.index), cbar_kws={'label': 'Temperature'},
                     vmin=np.amin(data2), vmax=np.amax(data2), cmap='hot')

# Add axis labels/rotations and title to the plot
plt.title('Temperature at Different Heights and Times')
plt.xlabel('Date')
plt.xticks(rotation=0)
plt.ylabel('Height')
plt.yticks(rotation=0)

我能够使用完整的日期时间字符串作为 x 刻度。另外,由于您要处理温度,因此我选择了“热”色标。

这是我的代码的输出: 热图


推荐阅读