代码之家  ›  专栏  ›  技术社区  ›  Joe

将标签从geom_label_Reject移动到ggplot页边距

  •  2
  • Joe  · 技术社区  · 6 年前

    在下面的图中,我想将标签“V-Engine”移动到绘图页边距中。调整 nudge_x

    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 回复  |  直到 6 年前
        1
  •  5
  •   Tung    6 年前

    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'
    

    于2018年11月16日由 reprex package (v0.2.1.9000)

    推荐文章