带有日期时间轴的 Seaborn 热图 [英] Seaborn Heatmap with Datetime Axes

查看:81
本文介绍了带有日期时间轴的 Seaborn 热图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I 并创建一个热图,其中 x 轴为年份,y 轴为月份.在热图中将是 % 的回报.这就是我所追求的.

I and to create a heatmap that will have year across the x axis and month across the y axis. In the heatmap will be % returns. Here's kinda what I am after.

所以我有一些数据并将它们转换为 pct_change() 系列.

So I have some data and I turn them into pct_change() series.

import pandas_datareader.data as web
import pandas as pd
from datetime import datetime as dt
import numpy as np
import seaborn as sns

start = dt(year = 2000, month = 1, day = 1)

df = web.DataReader('GDP', 'fred', start = '2000')
df.pct_change()
df.tail()

这就是我们正在处理的内容.需要注意的是,索引是一个 Datetime 对象.

So here's what we are working with. Important to note that the index is a Datetime object.

    GDP
DATE    
2016-10-01  18905.545
2017-01-01  19057.705
2017-04-01  19250.009
2017-07-01  19500.602
2017-10-01  19736.491

我想做这样的事情,但我不知道如何用日期时间索引来实现它

I want to do something like this, but I dont know how to implement it with the datetime index

gdp = df.pivot(df.index.month, df.index.year, "GDP")
ax = sns.heatmap(gdp)

哪个(预期)不起作用...

Which (expectedly) doesn't work...

KeyError: "Int64Index([ 1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,\n             4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,\n             7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7,\n            10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,  1,  4,  7, 10,\n             1,  4,  7, 10],\n           dtype='int64', name='DATE') not in index"

推荐答案

它不起作用,因为您正在 pivot 函数中提取月份和年份,而这些信息不在原始文件中df 你指定的.

It's not working because you are extracting the month and year in place within the pivot function, and those information is not in the original df you specified.

您可以预先指定它们:

df["Year"] = df.DATE.apply(lambda x: x.year)
df["Month"] = df.DATE.apply(lambda x: x.strftime("%B"))
df.pivot_table(index="Month",columns="Year",values="GDP", aggfunc="sum").fillna(0)
months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
pt = pt.reindex_axis(months)
sns.heatmap(pt, annot=True)

我正在重新索引行,因为在调用 pivot_table 时,它按升序对列或行进行排序,这不是通常对月份名称进行排序的方式.

I'm reindexing the rows because when calling pivot_table, it sorts columns or rows in ascending order, which is not how the month names are usually sorted.

以上给了我:

这篇关于带有日期时间轴的 Seaborn 热图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆