在matplotlib或seaborn中绘制没有日期的时间

时间:2018-09-12 09:05:19

标签: python pandas matplotlib seaborn

您好,我正在处理分类数据。我想查看特定日期的设备行为。我将这些作为数据框:

toronto_time上,我有一个datetime64[D]。我以前使用dt.time删除了日期。但是,它带来了一个数据类型问题,使其成为类型object而不是datetime64[D]。使用pd.to_datetime再次进行转换将为其添加日期。

所以我把它留给了原件:

       toronto_time             description
0      2018-09-08 00:00:50      STATS
1      2018-09-08 00:01:55      STATS
2      2018-09-08 00:02:18      DEV_OL
3      2018-09-08 00:05:24      STATS
4      2018-09-08 00:05:34      STATS
5      2018-09-08 00:06:33      CMD_ERROR

我尝试用以下代码对seaborn进行绘制:

import matplotlib.pyplot as plt
import matplotlib.dates as md
import seaborn as sns

plt.style.use('seaborn-colorblind')
plt.figure(figsize=(8,6))
sns.swarmplot('toronto_time', 'description', data=df);
plt.show()

但是,可视化在当天被压缩。我想删除xlabel中的日期,并根据小时数(0:00到24:00)进行拉伸

这就是我得到的: enter image description here

1 个答案:

答案 0 :(得分:1)

如果您的刻度仅在小时上,我不确定为什么要在图表上显示分钟和秒?但是您可以通过为轴设置格式器来实现。尽管我建议如果按小时查找刻度,也可以更改轴的限制。

import pandas as pd

import matplotlib.pyplot as plt
import matplotlib.dates as md
import seaborn as sns

df = pd.DataFrame({'toronto_time': ['2018-09-08 00:00:50',
                                    '2018-09-08 01:01:55',
                                    '2018-09-08 02:02:18',
                                    '2018-09-08 03:05:24',
                                    '2018-09-08 04:05:34',
                                    '2018-09-08 05:06:33'], 
                    'description': ['STATS', 'STATS', 'DEV_OL', 'STATS', 'STATS', 'CMD_ERROR']})
df['toronto_time'] = pd.to_datetime(df['toronto_time'], format='%Y-%m-%d %H:%M:%S')

plt.style.use('seaborn-colorblind')
fig, ax = plt.subplots(figsize=(8,6))
sns.swarmplot('toronto_time', 'description', data=df, ax=ax)
ax.set_xlim(df['toronto_time'].min()-pd.Timedelta(1,'h'),
            df['toronto_time'].max()+pd.Timedelta(1,'h'))
ax.xaxis.set_major_formatter(md.DateFormatter('%H:%M:%S'))

plt.show()

enter image description here

这是一个很好的示例,展示了如何使用定位器来定义刻度线的间距:http://leancrew.com/all-this/2015/01/labeling-time-series/