r - 在多个方面的可变 x 位置手动为 geom_area 添加颜色

标签 r ggplot2

这是 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 = 5x = 6.25facet 0红色的

来自 x = 6.25x = 10facet 0蓝色

来自 x = 6.25x = 7.5facet 1红色的

来自 x = 7.5x = 10facet 1蓝色

来自 x = 7.5x = 8.75facet 2红色的

来自 x = 8.75x = 10facet 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"))

... 等等:

enter image description here

关于r - 在多个方面的可变 x 位置手动为 geom_area 添加颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38384755/

相关文章:

r - 面板数据 : How to remove IDs with missing yearly information

根据 R 中的行号重组数据

r - 如何让 Shiny 等到你点击提交

r - 使用降序字母制作动画时防止标题空间更改

r - 如何在ggplot2中为hline添加图例

r - tidyr 和 rlang 错误

mysql - R中的selectInput从MySql获取数据

r - 将变量转换为 ggplot 的因子时遇到问题

r - 根据方面的存在有条件地修改ggplot主题?

r - 填充ggplot2 : geom_area()中折线图下的区域