3

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

Joe
  • 3,217
  • 3
  • 21
  • 37
  • Try adding `scale_x_continuous(limits = c(2, 7))` – d.b Nov 16 '18 at 23:32
  • @d.b, that is a clever suggestion, but introduces gridlines in space I would rather have as empty margin. Anyway to move labels beyond panel and into margin? – Joe Nov 16 '18 at 23:35

1 Answers1

6

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)

Tung
  • 26,371
  • 7
  • 91
  • 115