2016-07-14 36 views
4

這是df的一個粗略的估計我的工作:手動在變量x的位置增添色彩geom_area在多個方面

months <- 1:12 
age_y <- rep(0:2, 4) 
counts <- c(659, 508, 430, 303, 201, 180, 203, 318, 401, 500, 790, 630) 
df <- cbind.data.frame(months, age_y, counts) 
ggplot(df, aes(x = months, y = counts)) + geom_area() + facet_grid(.~age_y) 

我試圖做的是顏色的特定區域中的不同刻面不同的顏色。具體地,與上面的僞數據,我想的區域顏色:

x = 5x = 6.25facet 0紅色

x = 6.25x = 10facet 0藍色

x = 6.25x = 7.5facet 1紅色

x = 7.5x = 10 in facet 1 blu È

x = 7.5x = 8.75facet 2紅色

x = 8.75x = 10facet 2藍色

+0

'錯誤data.frame(... ,check.names = FALSE): 參數意味着不同的行數:12,11'請求編輯你的輸入數據。 – Miha

+0

@Miha抱歉,已修復。 – user6571411

回答

4

我想顏色的區域:
從X = 5至x = 6.25在小面0紅色
從x = 6.25到x = 10 in facet 0藍色
從x = 6.25到x = 7.5 in facet 1紅色

鑑於您的例子

library(ggplot2) 
months <- 1:12 
age_y <- rep(0:2, 4) 
counts <- c(659, 508, 430, 303, 201, 180, 203, 318, 401, 500, 790, 630) 
df <- cbind.data.frame(months, age_y, counts) 
ggplot(df, aes(x = months, y = counts)) + geom_area() + facet_grid(.~age_y) -> p 

你可以做

f <- lapply(split(df[,c("months", "counts")], df$age_y), function(dat) approxfun(dat$months, dat$counts)) 
p + scale_fill_identity() + 
    mapply(function(xmin,xmax,facet,col,res=.001) 
    geom_area(
    data = data.frame(
     age_y=facet, 
     months = seq(xmin, xmax, res), 
     counts = f[[facet]](seq(xmin, xmax, res)), 
     col = col), 
    aes(fill=col) 
), c(5,6.25,6.25),c(6.25,10,10),c("0","0","1"),c("red","blue", "blue")) 

...等等:

enter image description here