For the data:
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
I want to first plot the line for "cumulative" and then color it using the "time.period" variable. After that I want to fill in the area below the line using the same "time.period" variable. Here's my code for generating that plot:
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"))
This generates the following plot:
I then get a gap in the fill for year 2004. How can I adjust my code so that there are no breaks in the coloring for geom_area fill?
Since you are working with count data, I think it is reasonable to visualize your data using a bar chart. The figure will need to be cleaned up a bit, but this eliminates the broken part of the visualization.
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")