将类似日期时间的对象传递给seaborn.lmplot

Rob*_*bin 6 python datetime matplotlib pandas seaborn

我正在尝试使用seaborn线性模型图绘制一段时间内的值图,但出现错误

TypeError: invalid type promotion
Run Code Online (Sandbox Code Playgroud)

我读过不可能绘制大熊猫日期对象,但是鉴于seaborn要求您将大熊猫DataFrame传递到图中,这看起来确实很奇怪。

下面是一个简单的示例。有谁知道我该怎么做?

import pandas as pd
import seaborn as sns; sns.set(color_codes=True)
import matplotlib.pyplot as plt

date = ['1975-12-03','2008-08-20', '2011-03-16']
value = [1,4,5]
df = pd.DataFrame({'date':date, 'value': value})
df['date'] = pd.to_datetime(df['date'])

g = sns.lmplot(x="date", y="value", data=df, size = 4, aspect = 1.5)
Run Code Online (Sandbox Code Playgroud)

我正在尝试使用ggplot在r中创建这样的图,因此为什么要使用sns.lmplot 在此处输入图片说明

Pau*_*l H 5

您需要将日期转换为浮点数,然后格式化x轴以重新解释浮点数并将其格式化为日期。

这是我的处理方式:

import pandas
import seaborn
from matplotlib import pyplot, dates
%matplotlib inline

date = ['1975-12-03','2008-08-20', '2011-03-16']
value = [1,4,5]
df = pandas.DataFrame({
    'date': pandas.to_datetime(date),   # pandas dates
    'datenum': dates.datestr2num(date), # maptlotlib dates
    'value': value
})

@pyplot.FuncFormatter
def fake_dates(x, pos):
    """ Custom formater to turn floats into e.g., 2016-05-08"""
    return dates.num2date(x).strftime('%Y-%m-%d')

fig, ax = pyplot.subplots()
# just use regplot if you don't need a FacetGrid
seaborn.regplot('datenum', 'value', data=df, ax=ax)

# here's the magic:
ax.xaxis.set_major_formatter(fake_dates)

# legible labels
ax.tick_params(labelrotation=45)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明