对于数据:
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
我想首先绘制“累积”行,然后使用“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填充的着色没有中断?
答案 0 :(得分:1)
由于您正在使用计数数据,我认为使用条形图可视化您的数据是合理的。该图需要稍微清理一下,但这样可以消除可视化的破碎部分。
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")