Search code examples
rggplot2ggrepel

Move labels from geom_label_repel into ggplot margin


In the plot below I'd like to move the label "V-Engine" into the plot margin. Adjusting the nudge_x argument is moving the "S-Engine" label but not the "V-Engine" label.

library(ggplot2)
library(ggrepel)
library(dplyr)

ds <- 
    mtcars %>%
    mutate(vs = factor(vs, labels = c("V-Engine", "S-Engine"))) %>% 
    # Create labels for the rightmost data points
    group_by(vs) %>% 
        mutate(
            label = 
                case_when(
                    wt == max(wt) ~ as.character(vs), 
                    TRUE ~ NA_character_
                )
        ) %>%
    ungroup() 

ds %>% 
    ggplot(aes(x = wt, y = mpg, color = vs)) +
    geom_smooth(se=FALSE) + 
    geom_label_repel(aes(label = label), nudge_x = 1, na.rm = TRUE) + 
    guides(color = FALSE) + 
    theme_minimal() + 
    theme(plot.margin = unit(c(1,3,1,1), "cm")) 

enter image description here


Solution

  • You can set xlim() inside geom_label_repel

    library(dplyr)
    library(ggplot2)
    library(ggrepel)
    
    ds %>% 
      ggplot(aes(x = wt, y = mpg, color = vs)) +
      geom_smooth(se=FALSE) + 
      geom_label_repel(aes(label = label), 
                       nudge_x = 1, 
                       # direction = 'x',
                       xlim = c(0, 6.5),
                       na.rm = TRUE) + 
      guides(color = FALSE) + 
      theme_minimal() + 
      theme(plot.margin = unit(c(1,3,1,1), "cm")) +
      coord_cartesian(clip = 'off')
    #> `geom_smooth()` using method = 'loess' and formula 'y ~ x'
    

    Created on 2018-11-16 by the reprex package (v0.2.1.9000)