将标签从geom_label_repel移至ggplot边距

时间:2018-11-16 23:17:06

标签: r ggplot2 ggrepel

在下面的图中,我想将标签“ V-Engine”移到图中的空白处。调整nudge_x参数将移动“ S-Engine”标签,而不移动“ V-Engine”标签。

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

1 个答案:

答案 0 :(得分:3)

您可以在xlim()内设置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'

reprex package(v0.2.1.9000)于2018-11-16创建