2015-07-21 128 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