2

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

我的数据是:

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

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

rect<-data.frame(xmin = c(0.8, 0.8,0.8,0.8), xmax = c(2.2, 2.2, 2.2, 2.2), 
           ymin = c(430, 1130, 120, 80), ymax = c(550, 1230, 1500, 800), 
           alpha = c(.1, .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()

这给了我以下信息:使用注释代码绘图

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

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

根据 rect 数据框,我想要的只是每个方面的一个矩形。并非每个数据帧上的所有内容。现在忽略颜色,如果它们都是绿色或蓝色就可以了。

在此先感谢您的帮助。

4

1 回答 1

3

我认为这种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,1180,1450,750),
               Method=c(rep(c("A","B"),each=4)))

rect<-data.frame(xmin = c(0.8, 0.8,0.8,0.8), xmax = c(2.2, 2.2, 2.2, 2.2), 
                 ymin = c(430, 1130, 120, 80), ymax = c(550, 1230, 1500, 800), 
                 alpha = c(.1, .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 包于 2021-04-12 创建(v1.0.0)

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

于 2021-04-12T15:32:00.830 回答