R - ggplot2 - geom_area - 删除 geom_line 下的颜色填充中断

R - ggplot2 - geom_area - Remove break in color fill under a geom_line

对于数据:

   year     N cumulative time.period
1  2000   100        100        blue
2  2001   100        200        blue
3  2002   100        300        blue
4  2003   100        400        blue
5  2004   100        500        blue
6  2005   100        600         red
7  2006   100        700         red
8  2007   100        800         red
9  2008   100        900         red
10 2009   100       1000         red

我想先绘制 "cumulative" 的线,然后使用 "time.period" 变量为其着色。之后,我想使用相同的 "time.period" 变量填充线下方的区域。这是我生成该图的代码:

library(dplyr)
library(ggplot2)

year<-2000:2009
N <- rep(100, 10)

DF<-as.data.frame(cbind(year, N))

DF <- DF %>%
 mutate(cumulative = cumsum(N)) %>%
 mutate(time.period = ifelse(year<2005, "blue", "red"))

 ggplot(DF, aes(x=year, y=cumulative)) + 
  geom_line(color=DF$time.period) +
  ylab("Cumulative count") +
  geom_area(aes(fill=DF$time.period)) +
  scale_fill_manual(values=c("blue", "red"))

这会生成以下图:

然后我在 2004 年的填充中出现了空白。我如何调整我的代码以使 geom_area 填充的着色没有中断?

由于您使用的是计数数据,我认为使用条形图可视化数据是合理的。该图需要稍微清理一下,但这消除了可视化的损坏部分。

DF <- structure(list(year = 2000:2009, N = c(100L, 100L, 100L, 100L, 
100L, 100L, 100L, 100L, 100L, 100L), cumulative = c(100L, 200L, 
300L, 400L, 500L, 600L, 700L, 800L, 900L, 1000L), time.period =     
structure(c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L), 
.Label = c("blue", "red"), class = "factor")), 
.Names = c("year", "N", "cumulative", 
"time.period"), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10"))

ggplot(DF, aes(year, cumulative, fill = time.period)) +     
geom_bar(stat="identity", position = "identity")