为 ggplot

问题描述

我有一个数据框,我想在 4 个方面(通过 ID)呈现,并且对于每个方面,用矩形突出显示数据。

我的数据是:

dt<-data.frame(ID=c(rep(c("1","2","3","4"),2)),var=c(480,1180,170,130,500,1450,750),Method=c(rep(c("A","B"),each=4)))

我能找到的所有其他相关帖子都参考创建一个新的数据框,其中每个矩形的信息作为单独的行。因此,我创建了以下数据框:

rect<-data.frame(xmin = c(0.8,0.8,0.8),xmax = c(2.2,2.2,2.2),ymin = c(430,1130,120,80),ymax = c(550,1230,1500,800),alpha = c(.1,.1,.1),fill = c("red","green","orange","blue"))

我的 ggplot 代码是:

ggplot(dt,aes(x=Method,y=var)) +
  geom_point() +
  annotate("rect",xmin = rect$xmin,xmax = rect$xmax,ymin = rect$ymin,ymax = rect$ymax,alpha = 0.1,fill = "green")+
  facet_wrap(~ID,ncol=4)+
  theme_bw()

这给了我以下内容

Plot with annotate code

geom_rect 选项根本不适合我。我只是收到有关缺少变量的错误消息。我在 rect 数据框中添加一个 ID 和 Method 列,但这只会引发 var 变量没有存在的问题。我考虑过将其全部合并,但我不确定这会解决问题。这是我尝试使用 geom_rect

geom_rect(data=rect,aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax),fill = "blue")+

根据 rect 数据帧,我想要的只是每个面中的一个矩形。并非每个数据帧上的所有这些。暂时忽略颜色,如果它们都是绿色或蓝色就可以了。

预先感谢您的帮助。

解决方法

我认为 annotate() 方法不允许面特异性,因此 geom_rect() 可能是要走的路。您必须做的两件事是 (1) 设置 inherit.aes = FALSE 或将全局 aes() 更改为 geom_point() 层和 (2) 将方面信息添加到 rect data.frame .

library(ggplot2)

dt<-data.frame(ID=c(rep(c("1","2","3","4"),2)),var=c(480,1180,170,130,500,1450,750),Method=c(rep(c("A","B"),each=4)))

rect<-data.frame(xmin = c(0.8,0.8,0.8),xmax = c(2.2,2.2,2.2),ymin = c(430,1130,120,80),ymax = c(550,1230,1500,800),alpha = c(.1,.1,.1),fill = c("red","green","orange","blue"))

ggplot(dt,aes(x=Method,y=var)) +
  geom_point() +
  geom_rect(aes(xmin = xmin,xmax = xmax,ymin = ymin,ymax = ymax),alpha = 0.1,fill = "green",data = transform(rect,ID = as.character(1:4)),inherit.aes = FALSE) +
  facet_wrap(~ID,ncol=4)+
  theme_bw()

reprex package (v1.0.0) 于 2021 年 4 月 12 日创建

小旁注,如果您希望矩形逐字从 data.frame 中填充,您可以在矩形 fill = I(fill) 中使用 aes() (并删除 aes 之外的填充分配)。