将标签从geom_label_repel移动到ggplot边距 [英] Move labels from geom_label_repel into ggplot margin

查看:63
本文介绍了将标签从geom_label_repel移动到ggplot边距的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

推荐答案

您可以在 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日

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

这篇关于将标签从geom_label_repel移动到ggplot边距的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆