【问题标题】:seaborn plotting with datetime object使用 datetime 对象进行 seaborn 绘图
【发布时间】:2021-01-21 07:37:16
【问题描述】:

我不知道为什么每次我使用 seaborn 绘图时,它总是显示所有日期对象,如下所示。
我已经检查过我的“join_date”是一个对象而不是日期时间。
有谁知道问题出在哪里,我该如何解决?

【问题讨论】:

    标签: python pandas seaborn


    【解决方案1】:

    一种解决方案可能是您可以在使用to_period 方法进行绘图之前修改datetime object。这是一个例子:

    import pandas as pd
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    #generating some test data
    days = pd.date_range('1/1/2000', periods=8, freq='D')
    d2 = dict({'price': [10, 11, 9, 13, 14, 18, 17, 19]})
    df = pd.DataFrame(d2,index=days)
    print(df)
    
    #making join_date a datetime object
    #df['join_date'] = pd.to_datetime(df['join_date'])
    
    #setting join_date as index of the dataframe
    #df.set_index(['join_date'],inplace=True)
    
    #reducing the datetime object assuming the datetime is index and it is in pandas datetime format
    df.index = df.index.to_period("D") 
    
    #plotting the heatmap
    sns.heatmap(data=df)
    plt.tight_layout()
    plt.show()
    

    原始输出

    使用to_period后的最终输出

    【讨论】:

    • 添加了一个答案。请让我知道这对你有没有用。如果确实如此,请考虑接受赞成的答案。
    • 感谢您的帮助!但是我找到了一个直接的答案~显然在这个过程中日期对象被更改为日期时间索引,所以您只需将日期时间索引更改回str。您可以在使用 df.index.astype(str) 更改索引类型之后将数据透视表索引的类型检查为 type(df.index)
    • 谢谢。是的。这是一个很好的解决方案。但是,如果您使用时间序列分析,保留日期时间索引有很多优点。例如,您可以汇总结果并每月、每季度、每年绘制一次。根据时间过滤数据帧。因此,如果您打算进行更多分析,您可能需要考虑将其保留为日期时间格式。
    猜你喜欢
    • 1970-01-01
    • 2020-01-14
    • 2021-03-14
    • 2019-02-16
    • 2015-06-05
    • 2019-08-28
    • 2018-10-06
    相关资源
    最近更新 更多