0

我有以下ggplot: -

library(dplyr)
library(ggplot2)
library(ggtext)
library(ggdist)
set.seed(1)

DF = rbind(data.frame('Label' = 'A', val = rnorm(200, 5)), data.frame('Label' = 'B', val = rnorm(500, 10)))

DF %>%
ggplot(aes(x=Label, y=val, fill=Label, alpha = 1)) +
stat_dots() +
geom_textbox(x = -Inf, y = -Inf, label = 'My text', width = unit(0.4, "npc"), height = unit(0.04, "npc"), box.margin = unit(c(1, 1, 1, 1), "pt")) 

无论绘图窗口大小如何,我都想修复窗口区域的位置textboxbottom-left

然而,上面的代码未能达到同样的效果。我的绘图窗口出现以下错误

Error in grid.Call.graphics(C_upviewport, as.integer(n)) : 
  cannot pop the top-level viewport ('grid' and 'graphics' output mixed?)

我正在使用 R 和MacOS.

任何如何将 this 的位置固定在该位置的指针textbox都会bottom-left非常有帮助。

4

1 回答 1

1

确保 geom_textbox 中的 aes 和数据覆盖 ggplot()。

library(ggplot2)
library(ggtext)
library(ggdist)

set.seed(123)
DF <- rbind(data.frame('Label' = 'A', val = rnorm(200, 5)), 
            data.frame('Label' = 'B', val = rnorm(500, 10)))

ggplot(DF, aes(Label, val)) +
  stat_dots(aes(fill = Label)) +
  geom_textbox(aes(-Inf, -Inf, hjust = 0, vjust = 0, label = "My text"), 
    data.frame())

截屏

于 2021-10-20T18:20:55.680 回答