pandas 如何使用seaborn在x轴上将int绘制到日期时间?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45289482/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:05:09  来源:igfitidea点击:

How to plot int to datetime on x axis using seaborn?

pythonpandasmatplotlibseaborn

提问by Xavier

I am trying to use seaborn to plot a graph

我正在尝试使用 seaborn 绘制图形

sns.lmplot(x="when_start", y="how_long",hue= 'state',
           data=apps_pd.loc[(apps_pd['user'] == 'xavi')],lowess=True);

Where apps_pdis a dataframe. And fileds in apps_pd['when_start']are int like 1499963856220, and same for how_long.

其中apps_pd是一个数据帧。在apps_pd['when_start'] 中的文件是 int 像 1499963856220,和how_long 一样

Result of the script

脚本结果

However, I got a really messy graph if I don't change the format of the data.

但是,如果我不更改数据的格式,我会得到一个非常混乱的图表。

Is there anyway I could change the unit of x-axis to 'yyyy-mm-dd'? I want to group all my data in day level.

无论如何我可以将x轴的单位更改为'yyyy-mm-dd'吗?我想在日级别对我的所有数据进行分组。

And also could I change the unit of y-axis to hour-min-second?

我还可以将 y 轴的单位更改为小时-分-秒吗?

Here is the first 5 lines of my dataframe.

这是我的数据框的前 5 行。

回答by Serenity

First of all when you post data post it in text format not image.

首先,当您发布数据时,将其以文本格式而不是图像格式发布。

You can convert col when_startto date time format as follow:

您可以将 col 转换when_start为日期时间格式,如下所示:

apps_pd['when_start'] = pd.to_datetime(apps_pd['when_start'], unit='ms')

However scatter plot which is one of calls of lmplot does not support datetimeformat. You have to replace your xtick marks after plotting like in this example:

但是,作为lmplot调用之一的散点图不支持日期时间格式。在绘制后,您必须替换 xtick 标记,如下例所示:

import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt

cols = ['how_long', 'state', 'user', 'when_start']
data = [[62297, 'FINISHED', 'xavi', 1499963793923],
 [25761, 'FINISHED', 'xavi', 1499963446385],
 [20082, 'FINISHED', 'xavi', 1499963221203],
 [20508, 'FINISHED', 'xavi', 1499963156760],
 [580975, 'FINISHED', 'xavi', 1499962435293]]

apps_pd = pd.DataFrame(data, columns = cols)
# convert ms timestamps of dataframe to date time format by pandas
#apps_pd['when_start'] = pd.to_datetime(apps_pd['when_start'], unit='ms')
print (apps_pd)

sns.lmplot(x='when_start', y='how_long', hue= 'state',
 data=apps_pd[(apps_pd['user'] == 'xavi')],lowess=True)

# get current axis
ax = plt.gca()
# get current xtick labels
xticks = ax.get_xticks()
# convert all xtick labels to selected format from ms timestamp
ax.set_xticklabels([pd.to_datetime(tm, unit='ms').strftime('%Y-%m-%d\n %H:%M:%S') for tm in xticks],
 rotation=50)

plt.show()

enter image description here

在此处输入图片说明