【问题标题】:Fill area between multiple lines in plot填充绘图中多行之间的区域
【发布时间】:2018-06-20 15:50:31
【问题描述】:

我有一个 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')

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

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

有什么建议吗? 谢谢

【问题讨论】:

  • “填充线条的最小值和最大值之间的区域”是什么意思?是否应该填充线条下方的区域,直到填充线条的最小值?还是应该填充 0 和线之间的区域?还是……?
  • 试试polygon(c(b$time, rev(c$time)), c(b$y, rev(c$z)),col = "gray", border = "red")

标签: r plot lines fill area


【解决方案1】:

这是一种方法:

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

计算pminpmax

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

照常构造多边形:

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

或使用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))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多