回答:在几个图中相同的geom_rect

时间:2018-10-31 08:49:54

标签: r ggplot2

要在时间序列图中标记几个周期,我使用geom_rect

ggplot (peakflow, aes (x = Datum, y = l_min)) +
  geom_rect (xmin = as.Date ("2018-08-03"),
             xmax = as.Date ("2018-09-04"),
             fill = "palegreen",
             ymin = -Inf, ymax = Inf, alpha = 0.01) +
  geom_rect (xmin = as.Date ("2018-09-20"),
             xmax = as.Date ("2018-09-22"),
             fill = "palegreen",
             ymin = -Inf, ymax = Inf, alpha = 0.01) +
  geom_line (colour = "blue")

现在我有几个数据框,应该用相同的时间段标记,但是我不想在每个图上都添加geom_rect(因为不时添加了一个rect);这容易出错,而且不太舒服。

是否可以存储rect并在以后像使用它们

rects <- geom_rect (...) +
         geom_rect (...)
ggplot (peakflow, aes (x = Datum, y = l_min)) +
  rects + geom_line ()
ggplot (other_df, ...) +
  rects + geom_line ()

我知道:以上方法无效;还有另一种方法吗?

2 个答案:

答案 0 :(得分:0)

一种选择是如下使用lapply

# generate sample data
dat1 <- head(iris, 20)
dat2 <- tail(iris, 20)

plots <- lapply(list(dat1, dat2), function(x) {

  # replace this good with your function
  ggplot(data = x, mapping = aes(Sepal.Width, Sepal.Length)) +
    geom_point() +
    geom_smooth()

})

结果

plots[[1]]

enter image description here

plots[[2]]

enter image description here


如果您要存储geom,则可以

my_geoms <- function() {
  list(geom_point(),
       geom_smooth())
}

ggplot(dat1, mapping = aes(Sepal.Width, Sepal.Length)) + 
  my_geoms()

答案 1 :(得分:0)

如果要在一个对象中定义多个geom图层,请将其以a + b + ...而不是annotate()的形式放在列表中。

此外,从您的描述来看,geom_rect()rects <- list(annotate(geom = "rect", xmin = as.Date("2018-08-03"), xmax = as.Date("2018-09-04"), ymin = -Inf, ymax = Inf, fill = "palegreen", alpha = 0.5), annotate(geom = "rect", xmin = as.Date("2018-09-20"), xmax = as.Date("2018-09-22"), ymin = -Inf, ymax = Inf, fill = "palegreen", alpha = 0.5)) ggplot(df, aes(x = x, y = y)) + rects + geom_point() 更好地为您服务,因为set.seed(123) df <- data.frame( x = seq(as.Date("2018-07-01"), as.Date("2018-12-31"), 1), y = rnorm(184) ) 可以在您提供数据时使用数据框明确显示所有尺寸。

两个geom图层列表的插图(尽管在这种情况下,两个矩形实际上可以在同一图层中定义...):

{{1}}

样本数据:

{{1}}

plot

相关问题