当ggplot()为空且存在多个阴影的geom_rect时,基于geom_point进行构面

时间:2018-06-28 22:59:41

标签: r ggplot2 facet-wrap facet-grid

我正在尝试在散点图中绘制多个感兴趣的区域。基于this answer,我认为我被迫将初始ggplot()调用留空,并在geom_rect()调用之前提供geom_point()调用。我已经将所有这些工作了。但是,我无法基于传递到geom_point()的数据来应用构面。

以下内容正确绘制了我的数据(散布在不同大小的红色和蓝色区域上):

ggplot() + 
geom_rect(aes(xmin=885, xmax=1544, ymin=-Inf, ymax=Inf), alpha=.2, fill = "red") +
geom_rect(aes(xmin=1858, xmax=2580, ymin=-Inf, ymax=Inf), alpha=.2, fill = "blue") +
geom_point(data=df, aes(x=Position, y=Max_Freq))

但是,以下所有内容都会产生以下错误:

+ facet_wrap(~Replicate)
#Error in if (empty(data)) { : missing value where TRUE/FALSE needed

+ facet_wrap(data~Replicate)
#Error in combine_vars(data, params$plot_env, rows, drop = params$drop):
#  At least one layer must contain all variables used for facetting

+ facet_wrap(data$Replicate)
#Error in data$Replicate : object of type 'closure' is not subsettable

在其他图中,当在ggplot()调用中提供df时(即ggplot(df, aes(x=Position, y=Max_Freq)),第一个选项正确地将数据作为方面。诚然,我并不精通R,但是似乎应该有一个简单的解决方案。

1 个答案:

答案 0 :(得分:1)

一种方法是创建具有rect坐标的数据框,该rect坐标也将具有facet变量。示例:

一些数据:

df <- data.frame(x = rnorm(20),
                 y = runif(20),
                 facet = sample(c("A", "B"),
                                20,
                                replace = TRUE))

创建一个具有geom_rect坐标的数据框:

rect1 <- data.frame(xmin = -1,
                    xmax = 1,
                    ymin = -Inf,
                    ymax = Inf,
                    facet = c("A", "B"))

绘制它:

ggplot() + 
  geom_rect(data = rect1 , aes(xmin = xmin,
                               xmax = xmax,
                               ymin = ymin,
                               ymax = ymax),
            alpha = 0.2, fill = "blue") +
  geom_point(data = df, aes(x = x, y = y))+
  facet_wrap(~facet)

enter image description here

这允许按面定制矩形。示例:

rect2 <- data.frame(xmin = c(-1, 0),
                    xmax = c(0, 2),
                    ymin = c(-Inf, 0.25),
                    ymax = Inf,
                    facet = c("A", "B"))

ggplot() + 
  geom_rect(data = rect2 , aes(xmin = xmin,
                               xmax = xmax,
                               ymin = ymin,
                               ymax = ymax,
                               fill = facet),
            alpha = 0.2) +
  geom_point(data = df, aes(x = x, y = y))+
  facet_wrap(~facet)

enter image description here

或者只是在某些方面绘制矩形:

rect3 <- data.frame(xmin = -1,
                    xmax = 0, 
                    ymin = 0.25,
                    ymax = Inf,
                    facet = "A")

enter image description here