ggplot2:如何仅绘制时间序列的一部分

时间:2017-05-10 02:43:33

标签: r ggplot2

我想使用ggplot来绘制时间序列数据的部分内容。例如,假设我只想绘制这些数据的最后五个日期。是否需要在ggplot中指定此内容而不提前对数据进行子集化?我尝试使用xlim,但它没有用。

date <- c("2016-03-24","2016-03-25","2016-03-26","2016-03-27","2016-03-28",
              "2016-03-29","2016-03-30","2016-03-31","2016-04-01","2016-04-02")
Temp <- c(35,34,92,42,21,47,37,42,63,12)
df <- data.frame(date,Temp)

我的尝试:

ggplot(df) + geom_line(aes(x=date,y=Temp)) + xlim("2016-03-29","2016-04-02")

我的日期格式为POSIXct

1 个答案:

答案 0 :(得分:1)

您必须输入xlimas.Dateas.POSIXct()。这是你想要的吗?

df$date <- as.Date(df$date, format= "%Y-%m-%d", tz = "UTC")
ggplot(df) + geom_line(aes(x=date,y=Temp)) + 
xlim(as.Date(c("2016-03-30", "2016-04-02"), tz = "UTC", format = "%Y-%m-%d") )

enter image description here

PS:请注意,您将收到以下警告:

Warning message:
Removed 5 rows containing missing values (geom_path)