python - Pandas 数据框中列的热图

标签 python pandas matplotlib seaborn

我尝试根据一天中的天数和小时数(X-> 天数,Y-> 小时数)从 pandas 数据框生成热图。 结果应该是这样的:

enter image description here

数据源是postgres中的一张表:

   id    |       created_at       
---------+------------------------
 2558145 | 2017-03-02 11:31:15+01
 2558146 | 2017-03-02 11:31:46+01
 2558147 | 2017-03-02 11:32:28+01
 2558148 | 2017-03-02 11:32:57+01
....

这是我的代码,按小时重新组合数据。

import pandas as pd
from sqlalchemy import create_engine
engine = create_engine('postgresql://postgres:postgres@localhost:5432/bla')
import datetime
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
from matplotlib.dates import date2num
import seaborn as sns

df = pd.read_sql_query("""
SELECT created_at, 1 as print
FROM foo
WHERE created_at > '2017-02-01'
AND created_at < '2017-03-01'""", con=engine)

df['created_at'] = pd.to_datetime(df['created_at'])
df.index = df['created_at']

df = df.resample('H')['print'].sum()
df.fillna(0, inplace=True)

print(df.head())

created_at
2017-02-01 07:00:00+00:00      1.0
2017-02-01 08:00:00+00:00    152.0
2017-02-01 09:00:00+00:00    101.0
2017-02-01 10:00:00+00:00     92.0
2017-02-01 11:00:00+00:00    184.0
Freq: H, Name: print, dtype: float64

结果看起来不错,但我不知道如何绘制这个数据框?

最佳答案

热图是一个二维图,它将 x 和 y 对映射到一个值。这意味着热图的输入必须是二维数组。

在这里,您可能希望数组的列表示天数,行表示小时数。作为第一步,我们需要在数据框的两个不同列中包含天数和小时数。然后可以将这些列 reshape 为二维数组,这需要知道有多少天和多少小时。如果还要求每个天/小时对实际上都有一个条目。
没有这个限制,我们可以选择使用 pivot_table 来聚合表中的值。这显示在以下解决方案中。

import pandas as pd
import numpy as np; np.random.seed(0)
import seaborn.apionly as sns
import matplotlib.pyplot as plt

# create dataframe with datetime as index and aggregated (frequency) values
date = pd.date_range('2017-02-23', periods=10*12, freq='2h')
freq = np.random.poisson(lam=2, size=(len(date)))
df = pd.DataFrame({"freq":freq}, index=date)

# add a column hours and days
df["hours"] = df.index.hour
df["days"] = df.index.map(lambda x: x.strftime('%b-%d'))     
# create pivot table, days will be columns, hours will be rows
piv = pd.pivot_table(df, values="freq",index=["hours"], columns=["days"], fill_value=0)
#plot pivot table as heatmap using seaborn
ax = sns.heatmap(piv, square=True)
plt.setp( ax.xaxis.get_majorticklabels(), rotation=90 )
plt.tight_layout()
plt.show()

enter image description here

对于绘图,您还可以使用 matplotlib imshow 绘图,如下所示:

fig, ax = plt.subplots()
im = ax.imshow(piv, cmap="Greens")
fig.colorbar(im, ax=ax)

ax.set_xticks(range(len(piv.columns)))
ax.set_yticks(range(len(piv.index)))
ax.set_xticklabels(piv.columns, rotation=90)
ax.set_yticklabels(piv.index)
ax.set_xlabel("Days")
ax.set_ylabel("Hours")

plt.tight_layout()
plt.show()

enter image description here

关于python - Pandas 数据框中列的热图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43330205/

相关文章:

python - 从 pandas 数据框中重新排列条形图中的分组

python - 如何将贝塞尔曲线拟合到一组数据?

Python向路径字符串添加特殊字符

python - Pandas to_datetime() 没有检测到列

python - Matplotlib 事件和重新绘图

python - 如何在matplotlib中使用 `quiver()`获取单位向量?

python - 当你有一个名为 max 的变量时使用 Python 的 max 函数?

python - 为命名空间初始化模块中的类

python - Pandas:根据多列值删除或更改特定行

python - 将多个函数应用于多个 groupby 列