python - 使用带有日期时间数据的 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')
解决方案
我建议使用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 刻度。另外,由于您要处理温度,因此我选择了“热”色标。
推荐阅读
- python - 按组数对数据帧进行排序和过滤
- android - 如何在kotlin中舍入一个数字
- .htaccess - htaccess /en 工作正常,但 /en/ 给出页面找不到
- c# - PUBNUB - 订阅不适用于 .NET Windows 服务
- c - 在使用 strcpy 之前做一个 malloc 吗?
- java - 获取到vehicle和userApp类的实例后,如何将获取到的经纬度值传递给方法?
- java - 小于号 (<) 和大于号 (>) 在 Android Studio 中的大小或形状不同
- python - ModuleNotFoundError:没有名为“members.urls”的模块
- java - 使用 BinarySearch 的变体来查找双调数组中的最大值
- r - 均值插补法:图形表示?