填充图中多行之间的区域

时间:2023-02-09 17:32:15

I have got a plot with 3 lines as follows:

我有一个3行的情节如下:

a = data.frame(time = c(1:100), x = rnorm(100))
b = data.frame(time = c(1:100), y = rnorm(100))
c = data.frame(time = c(1:100), z = rnorm(100))

plot(a$time, a$x, type = 'l')
lines(b$time, b$y, type = 'l')
lines(c$time, c$z, type = 'l')

I need to fill the area between the lowest and maximum value of the lines so that I get a unique polygon of a given colour.

我需要在线的最低值和最大值之间填充区域,以便获得给定颜色的唯一多边形。

I know about the polygon function but I do not know how to use it in this case.

我知道多边形函数,但在这种情况下我不知道如何使用它。

Any suggestion? thanks

有什么建议吗?谢谢

1 个解决方案

#1


1  

Here is an approach:

这是一种方法:

a = data.frame(time = c(1:100), x = rnorm(100))
b = data.frame(time = c(1:100), y = rnorm(100))
c = data.frame(time = c(1:100), z = rnorm(100))

calculate the pmin and pmax:

计算pmin和pmax:

min_a <- pmin(a, b, c)
max_a <- pmax(a, b, c)

construct the polygon as usual:

像往常一样构造多边形:

polygon(c(c$time, rev(c$time)), c(max_a$x ,rev(min_a$x)), col = rgb(1, 0, 0,0.5) )

填充图中多行之间的区域

or using ggplot:

或使用ggplot:

library(tidyverse)
data.frame(a, b, c) %>% #combine the three data frames
  group_by(time) %>% # group by time for next step
  mutate(max = max(x, y, z), # calculate max of x, y, z in each time
         min = min(x, y, z)) %>% #same as above
  select(-time.1, - time.2) %>% #discard redundant columns
  gather(key, value, 2:4) %>% #convert to long format so you can color by key in the geom line call
  ggplot()+
  geom_ribbon(aes(x = time, ymin= min, ymax = max), fill= "red", alpha = 0.3)+
  geom_line(aes(x = time, y = value, color = key))

填充图中多行之间的区域

#1


1  

Here is an approach:

这是一种方法:

a = data.frame(time = c(1:100), x = rnorm(100))
b = data.frame(time = c(1:100), y = rnorm(100))
c = data.frame(time = c(1:100), z = rnorm(100))

calculate the pmin and pmax:

计算pmin和pmax:

min_a <- pmin(a, b, c)
max_a <- pmax(a, b, c)

construct the polygon as usual:

像往常一样构造多边形:

polygon(c(c$time, rev(c$time)), c(max_a$x ,rev(min_a$x)), col = rgb(1, 0, 0,0.5) )

填充图中多行之间的区域

or using ggplot:

或使用ggplot:

library(tidyverse)
data.frame(a, b, c) %>% #combine the three data frames
  group_by(time) %>% # group by time for next step
  mutate(max = max(x, y, z), # calculate max of x, y, z in each time
         min = min(x, y, z)) %>% #same as above
  select(-time.1, - time.2) %>% #discard redundant columns
  gather(key, value, 2:4) %>% #convert to long format so you can color by key in the geom line call
  ggplot()+
  geom_ribbon(aes(x = time, ymin= min, ymax = max), fill= "red", alpha = 0.3)+
  geom_line(aes(x = time, y = value, color = key))

填充图中多行之间的区域