ggplot2 - 使用循环对曲线下的几个区域进行着色

问题描述 投票:0回答:1

我想用不同的颜色对曲线下的不同区域进行着色。在这种情况下,尝试矢量化版本或 for() 循环不起作用(它可以用于绘制随附的注释,此处未显示)。

我没有使用下面所示的六个函数调用的语法,而是使用了以下行

highlight_area(tib, 1:6)
并收到以下错误消息:

Error in `ggplot2::geom_area()`:
! Problem while setting up geom aesthetics.
ℹ Error occurred in the 2nd layer.
Caused by error in `check_aesthetics()`:
! Aesthetics must be either length 1 or the same as the data (3003)
✖ Fix the following mappings: `fill`

这是我的代表:

library(ggplot2)
library(dplyr)
#> 
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#> 
#>     filter, lag
#> The following objects are masked from 'package:base':
#> 
#>     intersect, setdiff, setequal, union
library(tibble)

x_lower <-  seq(0.006, 0.0085, 0.0005)
x_upper <-  seq(0.0065, 0.009, 0.0005)
area_colors <- c("gray90", "gray80", "gray70", "gray50", "gray40", "black") 

highlight_area <- function(df, i) {
        geom_area(data = df |>
           filter(x >= x_lower[i] & x <  x_upper[i]),
           fill = area_colors[i])
}

tib <- 
    tibble(x = seq(0.006, 0.009, length.out = 6000),
                   y = dbeta(x, 300, 39700))

ggplot(tib, aes(x = x, y = y)) +
geom_line() +
highlight_area(tib, 1) +
highlight_area(tib, 2) +
highlight_area(tib, 3) +
highlight_area(tib, 4) +
highlight_area(tib, 5) +
highlight_area(tib, 6)

创建于 2023-09-26,使用 reprex v2.0.2

r for-loop ggplot2 vectorization
1个回答
0
投票

使用

lapply
你可以这样做:

library(ggplot2)

ggplot(tib, aes(x = x, y = y)) +
  geom_line() +
  lapply(1:6, highlight_area, df = tib)

© www.soinside.com 2019 - 2024. All rights reserved.