首页 > 解决方案 > ggplot注释grob位置不一致

问题描述

我正在尝试创建一系列在边距中包含注释的图形,这些图形应在图形中保持相同的绝对位置(这样如果按顺序查看多个图形,注释似乎不会移动)。

让 ggplot 允许在边距中进行注释而不扭曲图形本身是很复杂的,但我相信挑战已经解决(对于任何想知道的人,请参阅scales::squishclip = "off"线)。现在,不幸的是,我的注释(文本 grobs)在图表之间并不一致。

在下面的代码中,我创建了两个简单的数据框(实际上是 tibbles),然后从它们创建基本的 ggplots。数据集之间的代码相同,只是自变量的级别数(x 轴上的刻度)在图表之间有所不同。据推测,x轴上的这种不一致是问题的根源,但我不知道如何解决。

library(ggplot2)
library(grid)
library(dplyr)

dat1 = data.frame(IV = c(rep("GroupA",50),rep("GroupB",50)), 
                    DV = c(rnorm(n = 50, mean = 100, sd = 15),
                              rnorm(n = 50, mean = 115, sd = 15)))

dat2 = data.frame(IV = c(rep("GroupA",50),rep("GroupB",50),rep("GroupC",50),rep("GroupD",50)), 
                     DV = c(rnorm(n = 50, mean = 100, sd = 15),
                               rnorm(n = 50, mean = 115, sd = 15),
                               rnorm(n = 50, mean = 85, sd = 15),
                               rnorm(n = 50, mean = 100, sd = 30)))

tibdat1 = as_tibble(dat1) %>%
  group_by(IV) %>%
  summarise(
    M = mean(DV,na.rm=T))

tibdat2 = as_tibble(dat2) %>%
  group_by(IV) %>%
  summarise(
    M = mean(DV,na.rm=T))

graph1 = ggplot(data = tibdat1, mapping = aes(IV, M)) +
  geom_col() +
  scale_y_continuous(breaks = c(1:150), limits = c(1,150), oob = scales::squish) + 
  coord_cartesian(clip = "off") +
  annotation_custom(
    grob = textGrob(label = "myGrob1", gp = gpar(col = "red", fontsize = 13), rot = 90), ymin = 50, ymax = 50, xmin = .2, xmax = .2) 

graph2 = ggplot(data = tibdat2, mapping = aes(IV, M)) +
  geom_col() +
  scale_y_continuous(breaks = c(1:150), limits = c(1,150), oob = scales::squish) + 
  coord_cartesian(clip = "off") +
  annotation_custom(
    grob = textGrob(label = "myGrob2", gp = gpar(col = "blue", fontsize = 13), rot = 90), ymin = 50, ymax = 50, xmin = .2, xmax = .2) 

请注意,graph1 的 myGrob1 和 graph2 的 myGrob2 在 x 轴上的位置略有不同——这就是问题所在。

标签: rggplot2annotations

解决方案


推荐阅读