3

在下面的情节中,我想将标签“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")) 

在此处输入图像描述

4

1 回答 1

5

你可以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 包(v0.2.1.9000)于 2018 年 11 月 16 日创建

于 2018-11-16T23:49:38.740 回答