2015-07-21 94 views
2

对于数据下:的R - GGPLOT2 - geom_area - 颜色移除突破填补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 

我想先绘制了线的“累积”,然后使用“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")) 

这将生成以下情节:

Plot

然后我得到了填补空白的2004年,我如何调整我的代码,以便geom_area填充颜色没有中断吗?

回答

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") 

enter image description here