Move labels from geom_label_repel into ggplot margin

孤者浪人 提交于 2021-02-04 19:17:45

问题


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")) 


回答1:


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)



来源:https://stackoverflow.com/questions/53346606/move-labels-from-geom-label-repel-into-ggplot-margin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!