2016-07-14 44 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