Matplotlib TimeSeries热图可视化行修改

2024-04-19 13:07:18 发布

您现在位置:Python中文网/ 问答频道 /正文

提前感谢您的帮助

我试图从时间序列数据创建一个热图,该数据从年中开始,这导致热图的顶部向左移动,与图的其余部分不匹配(如下所示)。我该如何移动顶部的线条,以便数据的可视化与绘图的其余部分同步

(代码如下所示)

enter image description here

import pandas as pd
import matplotlib.pyplot as plt

# links to datadata
url1 = 'https://raw.githubusercontent.com/the-datadudes/deepSoilTemperature/master/minotDailyAirTemp.csv'

# load the data into a DataFrame, not a Series
# parse the dates, and set them as the index
df1 = pd.read_csv(url1, parse_dates=['Date'], index_col=['Date'])

# groupby year and aggregate Temp into a list
dfg1 = df1.groupby(df1.index.year).agg({'Temp': list})

# create a wide format dataframe with all the temp data expanded
df1_wide = pd.DataFrame(dfg1.Temp.tolist(), index=dfg1.index)

# ploting the data

fig, (ax1) = plt.subplots(ncols=1, figsize=(20, 5))


ax1.matshow(df1_wide, interpolation=None, aspect='auto');

Tags: csvthe数据importdataindexasplt
1条回答
网友
1楼 · 发布于 2024-04-19 13:07:18

现在,问题是什么,数据集上的日期,如果您看到数据集是从这个开始的

`1990-4-24,15.533`

为了解决这个问题,有必要添加1990/01/01-/04/23之间的数据,并删除2月29日的数据

rng = pd.date_range(start='1990-01-01', end='1990-04-23', freq='D')
df = pd.DataFrame(index= rng)
df.index = pd.to_datetime(df.index)
df['Temp'] = np.NaN
frames = [df, df1]
result = pd.concat(frames)
result = result[~((result.index.month == 2) & (result.index.day == 29))]

用这些数据

dfg1 = result.groupby(result.index.year).agg({'Temp': list})
df1_wide = pd.DataFrame(dfg1['Temp'].tolist(), index=dfg1.index)

# ploting the data

fig, (ax1) = plt.subplots(ncols=1, figsize=(20, 5))


ax1.matshow(df1_wide, interpolation=None, aspect='auto');

enter image description here

未填充部分的问题是数据集上NaN值的结果,在这种情况下,您可以选择将NaN值替换为列平均值或替换为行平均值。 可以使用其他方法替换NaN值

df1_wide = df1_wide.apply(lambda x: x.fillna(x.mean()),axis=0)

enter image description here

相关问题 更多 >