将类似日期时间的对象传递给seaborn.lmplot [英] Passing datetime-like object to seaborn.lmplot

查看:50
本文介绍了将类似日期时间的对象传递给seaborn.lmplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to do a plot of values over time using seaborn linear model plot but I get the error

TypeError: invalid type promotion

我读到无法绘制熊猫日期对象,但这似乎很奇怪,因为 seaborn 要求您将熊猫数据帧传递给图形.

I have read that it is not possible to plot pandas date objects, but that seems really strange given seaborn requires you pass a pandas DataFrame to the plots.

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

Below is a simple example. Does anyone know how I can get this to work?

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)

我正在尝试使用 ggplot 在 r 中创建这样的图,因此我想使用 sns.lmplot

I am trying to do a plot like this one I created in r using ggplot hence why I want to use sns.lmplot

推荐答案

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

You need to convert your dates to floats, then format the x-axis to reinterpret and format the floats into dates.

这是我要这样做的方式:

Here's how I would do this:

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)

这篇关于将类似日期时间的对象传递给seaborn.lmplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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