matplotlib/seaborn热图,使用pandas dataframe和datetime索引

2024-05-16 13:41:11 发布

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

我的数据框如下所示:

timestamp                   a           b           c           
2018-07-04 08:11:54.170     5.732026    7.930378    8.606152
2018-07-04 08:15:01.910     5.483141    8.040632    8.414517
2018-07-04 08:23:09.700     5.454963    7.634940    8.940616
2018-07-04 08:25:17.490     6.031954    7.256924    8.380531
2018-07-04 08:42:25.290     5.860383    7.488524    8.358526
2018-07-04 09:16:33.300     5.654590    7.697418    8.476449
2018-07-04 09:27:40.830     5.277766    7.817510    8.887601
2018-07-04 09:33:48.620     5.568183    7.752958    9.019584
2018-07-04 09:45:56.410     5.886682    7.326519    8.714343
2018-07-04 09:50:04.200     6.141217    7.462479    8.745352
2018-07-04 10:13:11.950     5.894507    7.515888    8.752824
2018-07-04 10:19:19.740     5.720255    7.387331    8.755654

它有一个包含日期时间戳的索引。其他3列有浮点值。在

我想用matplotlib/seaborn创建一个热图,如下所示(请注意x轴): desired heatmap

此图片是手动编辑的。在

下面是我的代码片段:

^{pr2}$

它只会产生这样糟糕的结果: enter image description here

问题是,我在和那些怪胎做斗争。如果有一个使用matplotlib的解决方案,那就更好了。提前非常感谢!在


Tags: 数据代码编辑matplotlib时间图片手动seaborn
2条回答

最后两行怎么样:

plt.xticks(rotation=45)
axHM = sns.heatmap(df.T, cmap='coolwarm', xticklabels=df.index.strftime('%H:%M'))

enter image description here

忘了matplotlib。。。仔细看看,这会让你达到你的目标!在

import pandas as pd
from plotly import __version__
from plotly.offline import init_notebook_mode, plot, iplot
import plotly.graph_objs as go
init_notebook_mode(connected=True)

df = pd.DataFrame()
df['timestamp']=['2018-07-04 08:11:54.170000', '2018-07-04 08:15:01.910000',
       '2018-07-04 08:23:09.700000', '2018-07-04 08:25:17.490000',
       '2018-07-04 08:42:25.290000', '2018-07-04 09:16:33.300000',
       '2018-07-04 09:27:40.830000', '2018-07-04 09:33:48.620000',
       '2018-07-04 09:45:56.410000', '2018-07-04 09:50:04.200000',
       '2018-07-04 10:13:11.950000', '2018-07-04 10:19:19.740000']
df['a']=[5.732026, 5.483141, 5.454963, 6.031954, 5.860383, 5.654590, 5.277766,
 5.568183, 5.886682, 6.141217, 5.894507, 5.720255]
df['b']=[7.930378, 8.040632, 7.634940, 7.256924, 7.488524, 7.697418, 7.817510,
 7.752958, 7.326519, 7.462479, 7.515888, 7.387331]
df['c']=[8.606152, 8.414517, 8.940616, 8.380531, 8.358526, 8.476449, 8.887601, 
 9.019584, 8.714343, 8.745352, 8.752824, 8.755654]    
df=df.set_index(['timestamp'])
df.index = pd.to_datetime(df.index)

z = []
z.append(list(df['c']))
z.append(list(df['b']))
z.append(list(df['a']))
data = [
go.Heatmap(
    z=z,
    x=df.index,
    y=['c','b','a'],
)
]

layout = go.Layout(
   xaxis = dict(ticks='', nticks=25),
   yaxis = dict(ticks='' )
)
fig = go.Figure(data=data, layout=layout)
iplot(fig)

玩得开心! enter image description here

相关问题 更多 >