Seaborn tsplot不能很好地显示x轴上的日期时间 [英] Seaborn tsplot does not show datetimes on x axis well

查看:619
本文介绍了Seaborn tsplot不能很好地显示x轴上的日期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面,我有以下脚本可以创建一个简单的时间序列图:

Below I have the following script which creates a simple time series plot:

%matplotlib inline
import datetime
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

df = []
start_date = datetime.datetime(2015, 7, 1)
for i in range(10):
    for j in [1,2]:
        unit = 'Ones' if j == 1 else 'Twos'
        date = start_date + datetime.timedelta(days=i)

        df.append({
                'Date': date.strftime('%Y%m%d'),
                'Value': i * j,
                'Unit': unit
            })

df = pd.DataFrame(df)

sns.tsplot(df, time='Date', value='Value', unit='Unit', ax=ax)
fig.autofmt_xdate()

结果如下:

如您所见,x轴的日期时间有奇数,而不是matplotlib和其他绘图工具附带的通常的"nice"表示.我尝试了很多事情,重新格式化了数据,但是它永远不会干净.有人知道吗?

As you can see the x-axis has strange numbers for the datetimes, and not the usual "nice" representations that come with matplotlib and other plotting utilities. I've tried many things, re-formatting the data but it never comes out clean. Anyone know a way around?

推荐答案

Matplotlib将日期表示为浮点数(以天为单位),因此,除非您(或熊猫或seaborn)告诉您您的值表示日期,否则它将不能将刻度线格式化为日期.我不是专家,但看起来它(或熊猫)确实将datetime对象转换为matplotlib日期,但是没有为轴分配适当的定位符和格式化程序.这就是为什么您得到这些奇怪的数字的原因,这些数字实际上只是从0001.01.01开始的日子.因此,您必须手动处理刻度线(在大多数情况下,刻度线会更好,因为它可以为您提供更多控制权).

Matplotlib represents dates as floating point numbers (in days), thus unless you (or pandas or seaborn), tell it that your values are representing dates, it will not format the ticks as dates. I'm not a seaborn expert, but it looks like it (or pandas) does convert the datetime objects to matplotlib dates, but then does not assign proper locators and formatters to the axes. This is why you get these strange numbers, which are in fact just the days since 0001.01.01. So you'll have to take care of the ticks manually (which, in most cases, is better anyways as it gives you more control).

因此,您必须分配一个日期定位器,该决定器将确定在何处放置刻度线,然后使用日期格式化程序,它将格式化字符串刻度标签.

So you'll have to assign a date locator, which decides where to put ticks, and a date formatter, which will then format the strings for the tick labels.

import datetime
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# build up the data
df = []
start_date = datetime.datetime(2015, 7, 1)
for i in range(10):
    for j in [1,2]:
        unit = 'Ones' if j == 1 else 'Twos'
        date = start_date + datetime.timedelta(days=i)

        # I believe it makes more sense to directly convert the datetime to a
        # "matplotlib"-date (float), instead of creating strings and then let
        # pandas parse the string again
        df.append({
                'Date': mdates.date2num(date),
                'Value': i * j,
                'Unit': unit
            })
df = pd.DataFrame(df)

# build the figure
fig, ax = plt.subplots()
sns.tsplot(df, time='Date', value='Value', unit='Unit', ax=ax)

# assign locator and formatter for the xaxis ticks.
ax.xaxis.set_major_locator(mdates.AutoDateLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y.%m.%d'))

# put the labels at 45deg since they tend to be too long
fig.autofmt_xdate()
plt.show()

结果:

这篇关于Seaborn tsplot不能很好地显示x轴上的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆