Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
513 views
in Technique[技术] by (71.8m points)

r - Fill area between multiple lines in plot

I have got a plot with 3 lines as follows:

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

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) )

enter image description here

or using 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))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...