Search code examples
rggplot2ggtext

Fixing the position of Text box in plot window in ggplot


I have below 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")) 

I wanted to fix the position of the textbox at the bottom-left region of the window irrespective of the plot window size.

However above code is failing to achieve the same. I am getting below error with my plot window

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

I am using R with MacOS.

Any pointer how to fix the position of this textbox at the bottom-left position will be very helpful.


Solution

  • Be sure that aes and data in geom_textbox override 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())
    

    screenshot