这是 df
的粗略近似值我正在与:
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 = 5
至 x = 6.25
在 facet 0
红色的来自
x = 6.25
至 x = 10
在 facet 0
蓝色来自
x = 6.25
至 x = 7.5
在 facet 1
红色的来自
x = 7.5
至 x = 10
在 facet 1
蓝色来自
x = 7.5
至 x = 8.75
在 facet 2
红色的来自
x = 8.75
至 x = 10
在 facet 2
蓝色
最佳答案
I would like to color the area:
From x = 5 to x = 6.25 in facet 0 red
From x = 6.25 to x = 10 in facet 0 blue
From x = 6.25 to x = 7.5 in facet 1 red
鉴于你的例子
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"))
... 等等:
关于r - 在多个方面的可变 x 位置手动为 geom_area 添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384755/