【问题标题】:Passing datetime-like object to seaborn.lmplot将类似日期时间的对象传递给 seaborn.lmplot
【发布时间】:2018-07-29 08:23:11
【问题描述】:

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

TypeError: invalid type promotion

我已经读到无法绘制 pandas 日期对象,但这似乎真的很奇怪,因为 seaborn 要求您将 pandas 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)

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

【问题讨论】:

标签: python pandas datetime matplotlib seaborn


【解决方案1】:

您需要将日期转换为浮点数,然后格式化 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)

【讨论】:

  • TypeError: formatter 参数应该是 matplotlib.ticker.Formatter 的实例
  • @FlorinAndrei 该示例仍在现代 python/matplotlib/seaborn 上运行,因此我不确定您对复制/粘贴错误消息的期望。
【解决方案2】:

我从 Paul H. 那里找到了一个派生解决方案,用于在 seaborn 中绘制时间戳。由于返回了一些后端错误消息,我不得不将它应用于我的数据。

在我的解决方案中,我在 ax.xaxis.set_major_formatter 上添加了一个 matplotlib.ticker FuncFormatter。这个 FuncFormatter 包装了 fake_dates 函数。这样,就不需要事先插入@pyplot.FuncFormatter。

这是我的解决方案:

import pandas
import seaborn
from matplotlib import pyplot, dates
from matplotlib.ticker import FuncFormatter

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
})


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(FuncFormatter(fake_dates))

# legible labels
ax.tick_params(labelrotation=45)

fig.tight_layout()

我希望这有效。

【讨论】:

    猜你喜欢
    • 2022-09-24
    • 2018-12-06
    • 2019-04-29
    • 2017-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多