简体   繁体   English

Plotly:如何使用日期值创建热图?

[英]Plotly: How to create a heatmap with date values?

I have a pandas DataFrame with columns = [A, B, C, D] and rows = [a, b, c, d]. I have a pandas DataFrame with columns = [A, B, C, D] and rows = [a, b, c, d]. Each cell of my dataframe has a specifc date.我的 dataframe 的每个单元格都有一个特定的日期。 I want to create a heatmap were later dates are colored diferent than earlier dates.我想创建一个热图,因为较晚的日期与较早的日期颜色不同。

I managed to do something with plotly by converting my datetime variable to timestamp.通过将我的日期时间变量转换为时间戳,我设法用 plotly 做一些事情。 But I want to annotate each cell with the datetime(timestamp).但我想用日期时间(时间戳)注释每个单元格。 Is there a way to do that with Plotly?有没有办法用 Plotly 做到这一点?

You can use the same approach as in the answer to Plotly: How to round display text in annotated heatmap but keep full format on hover?您可以使用与Plotly 的答案相同的方法:How to round display text in annotated heatmap but keep full format on hover? as long as you handle your dates as a number value for the heatmap input, and grab the dates as string for your annotations.只要您将日期作为热图输入的数字值处理,并将日期作为字符串用于注释。 I like to juggle between pd.Timestamp() and to_pydatetime() and set an epoch such as datetime.datetime(1970,1,1) to calculate time differences against.我喜欢在pd.Timestamp()to_pydatetime()之间切换,并设置一个诸如datetime.datetime(1970,1,1)之类的纪元来计算时差。 The heatmap below is produced from a pandas dataframe with dates as strings.下面的热图由 pandas dataframe 生成,日期为字符串。 Let me know id you'd like to start with a dataframe with dates of any other format.如果您想从 dataframe 开始,请告诉我任何其他格式的日期。

Data数据

data = {'A': ['2020-6-6', '2020-10-10', '2020-12-12'],
        'B': ['2019-6-6', '2019-10-10', '2019-12-12'],
        'C': ['2018-6-6', '2018-10-10', '2018-12-12']}

Heatmap热图

在此处输入图像描述

Code代码

import plotly.express as px
import plotly.figure_factory as ff
import pandas as pd
import datetime

# source is a pandas dataframe with dates as strings
data = {'A': ['2020-6-6', '2020-10-10', '2020-12-12'],
        'B': ['2019-6-6', '2019-10-10', '2019-12-12'],
        'C': ['2018-6-6', '2018-10-10', '2018-12-12']}
dfi = pd.DataFrame(data)

# grab dates as strings for use as labels later
z_text = [[y for y in x] for x in dfi.values.tolist()]

# convert df to pandas datetime
dfi = dfi.apply(pd.to_datetime)

# set epoch
epoch = datetime.datetime(1970,1,1)

# convert difference in days from all dates to epoch
# to use as input for color scheme in heatmap
days = [[ (pd.Timestamp(r).to_pydatetime()-epoch).days for r in dfi[col].values] for col in dfi.columns]
df = pd.DataFrame(days)
df.columns, df.index = dfi.columns,  dfi.columns
z = df.values.tolist()

# build heatmap
fig = ff.create_annotated_heatmap(z, x=list(df.columns),
                                     y=list(df.columns),
                                     annotation_text=z_text, colorscale='agsunset')

# add title
fig.update_layout(title_text='<i><b>Heatmap with dates</b></i>',
                  #xaxis = dict(title='x'),
                  #yaxis = dict(title='x')
                 )

# add custom xaxis title
fig.add_annotation(dict(font=dict(color="black",size=14),
                        x=0.5,
                        y=-0.15,
                        showarrow=False,
                        text="",
                        xref="paper",
                        yref="paper"))

# add custom yaxis title
fig.add_annotation(dict(font=dict(color="black",size=14),
                        x=-0.35,
                        y=0.5,
                        showarrow=False,
                        text="",
                        textangle=-90,
                        xref="paper",
                        yref="paper"))

# adjust margins to make room for yaxis title
# fig.update_layout(margin=dict(t=50, l=200))
# add colorbar
# fig['data'][0]['showscale'] = True

fig.show()

I used seaborn for heatmaps.我使用 seaborn 作为热图。

import pandas as pd
import seaborn as sns

df = pd.read_csv('Dataset.csv')

Heatmap
sns.set(rc={'figure.figsize':(11.7,8.27)})
sns.heatmap(df.corr().round(2),square=True,cmap="RdYlGn",annot=True)

Documentation: https://seaborn.pydata.org/generated/seaborn.heatmap.html文档: https://seaborn.pydata.org/generated/seaborn.heatmap.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM