【问题标题】:Seaborn heatmap between date column and integer column日期列和整数列之间的 Seaborn 热图
【发布时间】:2021-04-11 18:41:48
【问题描述】:

我有一个包含'Date' 列和'Tweet_Count' 列的数据框。

我想绘制一张热图,显示一个月中每一天的推文计数。

使用此代码:

uk = uk_df.pivot("Date", "Tweet_Count")
ax = sns.heatmap(uk)

我收到一个错误:

TypeError: '<=' not supported between instances of 'float' and 'str'

任何帮助将不胜感激。谢谢。

【问题讨论】:

  • 它看起来像 seaborn 热图 require a 2D array as input。您可能需要重新考虑如何表示日期数据 - 例如,x 轴是星期几,y 轴是星期数。这假设您仅尝试绘制 1 个国家/地区。

标签: python dataframe plot seaborn heatmap


【解决方案1】:

您正在寻找的sns.heatmap所需的DataFrame格式是一个数据透视表,其中indexcolumnsvalues作为DateCountryTweet_Count传递给pivot ,分别如下(如果这导致错误,请升级到pandas 的最新版本,因为pivot 在过去的版本中有问题):

   Country    UK
      Date  
2020-03-01  400
2020-03-02  1000
2020-03-03  100

因此,您只需将 Country 也传递给枢轴:

uk = pd.DataFrame({'Country': {0: 'UK', 1: 'UK', 2: 'UK'},
 'Date': {0: '2020-03-01', 1: '2020-03-02', 2: '2020-03-03'},
 'Tweet_Count': {0: 100, 1: 200, 2: 300}})

uk['Date'] = pd.to_datetime(uk['Date']).dt.date

uk = uk.pivot("Date", "Country", 'Tweet_Count')
ax = sns.heatmap(uk)

向下滚动到第四块代码here

值得一提的是,您还可以使用以下方式进行注释:

ax = sns.heatmap(uk, annot=True, fmt="d")

【讨论】:

    【解决方案2】:

    假设数据是这样的,下面我有两个国家

    import pandas as pd
    import numpy as np
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    Date = pd.date_range(start='1/3/2020', periods=30,freq="D").strftime('%Y-%m-%d').to_list()
    df = pd.DataFrame({'Country':np.repeat(['UK','KU'],len(Date)),
                       'Date':Date*2,
                         'Tweet_Count':np.random.randint(1000,2000,len(Date)*2)})
    df.head()
    
        Country Date    Tweet_Count
    0   UK  2020-01-03  1809
    1   UK  2020-01-04  1419
    2   UK  2020-01-05  1463
    3   UK  2020-01-06  1576
    4   UK  2020-01-07  1137
    

    如果只有 1 个国家/地区,则可以转置:

    fig, ax = plt.subplots(figsize=(8,2))
    uk = df[df['Country']=="UK"]
    ax = sns.heatmap(uk[['Date','Tweet_Count']].set_index('Date').T)
    

    如果有 2 个或更多:

    wide_df = df.pivot_table(index="Country",columns="Date",fill_value="Tweet_Count")
    wide_df.columns = [j for i,j in wide_df.columns]
    fig, ax = plt.subplots(figsize=(8,2))
    ax = sns.heatmap(wide_df)
    

    【讨论】:

      猜你喜欢
      • 2018-08-10
      • 2017-04-16
      • 2021-04-07
      • 2018-05-15
      • 2015-09-12
      • 2020-10-12
      • 1970-01-01
      • 2018-01-02
      相关资源
      最近更新 更多