Home > Software engineering >  geom_text from separate file outside of initial plot area
geom_text from separate file outside of initial plot area

Time:10-26

I have the following two dataframes

df <- data.frame(Groesse=c("A", "B", "C", "D"),
                  x=c(0, 1, 30, 25),
                  y=c(0, 90, 85, 20))


df_text <- data.frame(Groesse=c("X", "Y"),
                 x=c(1, 30),
                 y=c(105, 105))

and tried to achieve what I want with the following:

plot <- ggplot(df)  
    geom_point(aes(x, y))  
    geom_text(data = df_text, aes(x, y, label = "Groesse"))  
    scale_y_continuous(limits = c(0,100), expand = c(0,0))  
    coord_cartesian(clip = "off")  
    theme(plot.margin = unit(c(10, 1, 1, 1), "lines"))

plot

I would like to have the annotations (using geom_text()) to be above the scatterplot, but outside of the plot area. However, my plot is missing the values from geom_text().

Plot without text

Desired output (just a sketch):

Desired Output

Any idea how I can add the text outside the plot area without producing two different plots and then combining those in a grid?

CodePudding user response:

In addition to turning clipping off in the co-ordinates function, you need to set the out-of-bounds oob argument in scale_y_continuous() so the data isn't censored.

ggplot(df)  
  geom_point(aes(x, y))  
  geom_text(data = df_text, aes(x, y, label = "Groesse"))  
  scale_y_continuous(limits = c(0,100), expand = c(0,0), oob = ~ .x)  
  coord_cartesian(clip = "off")  
  theme(plot.margin = unit(c(10, 1, 1, 1), "lines"))

enter image description here

CodePudding user response:

This is just to point out an alternative to using geom_text() for annotations. For continuous axes, you can use the secondary axis to add some annotations.

library(ggplot2)

df <- data.frame(Groesse=c("A", "B", "C", "D"),
                 x=c(0, 1, 30, 25),
                 y=c(0, 90, 85, 20))


df_text <- data.frame(Groesse=c("X", "Y"),
                      x=c(1, 30),
                      y=c(105, 105))

ggplot(df)  
  geom_point(aes(x, y))  
  scale_y_continuous(
    limits = c(0,100), expand = c(0,0)
  )  
  scale_x_continuous(
    sec.axis = sec_axis(
      ~.x, name = NULL, breaks = c(1, 30),
      labels = rep("Groesse", 2)
    )
  )  
  theme(
    axis.ticks.length.x.top = unit(0, "pt"),
    axis.text.x.top = element_text(margin = margin(b = 10))
  )

Created on 2022-10-26 by the enter image description here

  • Related