gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:01:18 29 4
gpt4 key购买 nike

我正在尝试使用 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 enter image description here

最佳答案

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

这是我将如何做到这一点:

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)

enter image description here

关于python - 将类似日期时间的对象传递给 seaborn.lmplot,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48860428/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com