简体   繁体   English

ValueError:第 0 年超出范围 seaborn

[英]ValueError: year 0 is out of range seaborn

I am struggling to plot a simple time series with seaborn and can't understand why this hasn't work.我正在努力用 seaborn 绘制一个简单的时间序列,但不明白为什么这不起作用。 My dataframe time_series give daily data for patients from 2015 to 2019 and also has a datetime index.It looks as such:我的数据帧time_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

I am trying to build a scatter plot, however upon building it, it starts at 2000 and therefore all the data points are to the right of the graph.我正在尝试构建一个散点图,但是在构建它时,它从 2000 开始,因此所有数据点都在图表的右侧。 I tried to counter this by setting an xlim but am receiving a strange error.我试图通过设置xlim来解决这个问题,但收到一个奇怪的错误。 My code is as such:我的代码是这样的:

import seaborn as sns
import matplotlib.pyplot as plt

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

This is the error which I don't understand as I have no year '0':这是我不明白的错误,因为我没有年份“0”:

ValueError: year 0 is out of range

Can anyone help me out here.有人可以帮我从这里出去吗。 Many Thanks非常感谢

  • The issue seems to be that the datetime information from the df.index is converted to a datetime ordinal representation for the plot locs .问题似乎是来自df.indexdatetime信息被转换为 plot locs的日期时间序数表示。
  • If you use locs, labels = plt.xticks() , comment out plt.xlim and print locs , you will see they are array([729390.00000485, 730120.00000485, 730851.00000485, 731581.00000485, 732312.00000485, 733042.00000485, 733773.00000485, 734503.00000485, 735234.00000485, 735964.00000485]) .如果你使用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]) So when you set plt.xlim(2015, 2019) you are not in the range of the locs being plotted.因此,当您设置plt.xlim(2015, 2019)您不在绘制的locs范围内。 The years are just labels.岁月只是标签。
  • Given your sample dataframe with the a datetime index给定带有日期时间索引的示例数据框
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()

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM