删除ggplot中缺少日期之间的连接线 [英] Removing connetion lines between missing Dates in ggplot

查看:41
本文介绍了删除ggplot中缺少日期之间的连接线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想绘制一个缺少日期和值的时间序列.这是一个示例:

I want to plot a time series with missing dates and values. Here is an example:

library(lubridate)
date_list = seq(ymd('1990-05-01'),ymd('2000-09-30'),by='day')
date_list = date_list[which(month(date_list) %in% c(5:9))]

value_list1 = sample(1:40, 1683, replace=TRUE)
value_list2 = sample(1:40, 1683, replace=TRUE)

testsample = data.frame(Date = date_list, Value1 = value_list1, Value2 = value_list2)

library(ggplot2)
ggplot(data = testsample, aes(x = Date)) +
  geom_line(aes(y = Value1), color = "black", size = 1, alpha=0.5) +
  geom_line(aes(y = Value2), color = "red", size = 1, alpha=0.5) +
  labs(subtitle="testplot", 
       x = "year", 
       y = "values") +
  scale_x_date(date_labels="%y",date_breaks  ="1 year")

我没有从11月到4月的日期和数据.

I have no dates and data from November to April.

我的情节看起来像这样:

My plot looks like this:

如何删除年份之间的那些连接线?我读过有关将日期转换为因子的信息,但是对此我不确定.还有其他解决方案吗?

How can I remove those connection lines between the years? I read about transforming the dates into factors, but I am not sure about this. Is there another solution?

推荐答案

一种解决方案是指定组的外观,以匹配要通过线连接的组.

One solution would be to specify the group aesthetics to match the groups you want to have connected by lines.

在您的情况下,这是年份:

In your case this is the year:

ggplot(data = testsample, aes(x = Date, group = year(Date))) +
  geom_line(aes(y = Value1), color = "black", size = 1, alpha=0.5) +
  geom_line(aes(y = Value2), color = "red", size = 1, alpha=0.5) +
  labs(subtitle="testplot", 
       x = "year", 
       y = "values") +
  scale_x_date(date_labels = "%y", date_breaks  ="1 year")

基于Gregors注释,我们还可以将隐式缺失值更改为显式缺失值,例如使用 tidyr :: complete :

Building on Gregors comment we can also change implicit missing values to explicit missing values, e.g. using tidyr::complete:

testsample2 <- tidyr::complete(testsample, Date = seq(min(Date), max(Date), by = "day"))
ggplot(data = testsample2, aes(x = Date)) +
  geom_line(aes(y = Value1), color = "black", size = 1, alpha=0.5) +
  geom_line(aes(y = Value2), color = "red", size = 1, alpha=0.5) +
  labs(subtitle="testplot", 
       x = "year", 
       y = "values") +
  scale_x_date(date_labels = "%y", date_breaks  ="1 year")

这篇关于删除ggplot中缺少日期之间的连接线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆