ValueError:0年超出seaborn的范围

2024-10-01 07:41:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力用seaborn绘制一个简单的时间序列,但我不明白为什么这不起作用。我的dataframetime_series提供了2015年至2019年患者的每日数据,并且还有一个datetime索引。它看起来是这样的:

            patients
Date                
2015-01-04        49
2015-01-05        51
2015-01-06        48
2015-01-07        30
2015-01-08        27

我试图建立一个散点图,但是在建立它之后,它从2000年开始,因此所有的数据点都在图的右边。我试图通过设置xlim来解决这个问题,但收到了一个奇怪的错误。我的代码如下:

import seaborn as sns
import matplotlib.pyplot as plt

sns.scatterplot(x=time_series.index, y=time_series['patients'])
plt.xlim(2015,2019)

这是我不理解的错误,因为我没有年份“0”:

ValueError: year 0 is out of range

有人能帮我吗。非常感谢


Tags: 数据importtimeas错误时间绘制plt
1条回答
网友
1楼 · 发布于 2024-10-01 07:41:22
  • 问题似乎是来自df.indexdatetime信息被转换为绘图locs的日期时间顺序表示
  • 如果您使用locs, labels = plt.xticks(),注释掉plt.xlim并打印locs,您将看到它们是array([729390.00000485, 730120.00000485, 730851.00000485, 731581.00000485, 732312.00000485, 733042.00000485, 733773.00000485, 734503.00000485, 735234.00000485, 735964.00000485])。因此,当您设置plt.xlim(2015, 2019)时,您不在正在绘制的locs范围内。岁月只是标签
  • 给定带有日期时间索引的示例数据帧
from datetime import date, datetime

# determine ordinal value for desired date range
print(date.toordinal(datetime(2015, 1, 1, 0, 0)))
>>>735599
print(date.toordinal(datetime(2019, 1, 1, 0, 0)))
>>>737060

chart = sns.scatterplot(x=df.index, y=df['patients'])
plt.xlim(735599, 737060)

plt.setp(chart.get_xticklabels(), rotation=45)
plt.show()

enter image description here

相关问题 更多 >