从带填充的连续日期数据创建带年条的箱线图

create boxplot with year bars from continuous date data with fill

我正在尝试制作一个箱线图,其中包含两个不同的填充物,其中包含多年的连续日期数据(但每年只有一个柱状图)。我的数据看起来很简单:

date,       number,  type
2007-06-07  2        tot
2007-06-09  3        tot
2007-06-12  0        gps

所以我导入了我的数据并使用 as.Date 函数格式化了日期并且它起作用了。我将所有的 NA 都更改为 0。然后我尝试了以下代码:

p1 <- ggplot(sights, aes(x =date, y = number, group=date, fill = type)) + 
 geom_boxplot(alpha=0.7)

 p1

我得到了这样一个情节: plot

所以我尝试了如下代码:

  p1 <- p1+scale_x_date(breaks = as.Date(c("2005", "2006", "2007","2009", "2010", "2011", "2012", "2013",  "2014","2015", "2016","2017","2018")))                                          
p1

但它不起作用。能得到一些帮助真是太棒了!我也想在一个月后做同样的事情 ;)

编辑:我在 2101 年左右有一些异常值。我删除了它们,现在我得到: plot2

这个输出接近你想要的吗?

sights %>% 
  mutate(year = format.Date(date, "%Y")) %>% 
  ggplot(aes(x = year, y = number, fill = type)) + 
  geom_boxplot(alpha=0.7)