Override horizontal positioning with ggrepel

后端 未结 2 1923
鱼传尺愫
鱼传尺愫 2020-12-07 03:39

I\'m working on a chart similar to a slopegraph, where I\'d like to put labels along one or both sides with ample blank space to fit them on both sides. In cases where label

2条回答
  •  一整个雨季
    2020-12-07 04:15

    UPDATE (12 December 2019):

    FYI, this is now addressed in the development version of ggrepel, and the fix also applies to geom_label_repel. See issue #137 on GitHub.

    library(ggplot2)
    library(dplyr)
    devtools::install_github("slowkow/ggrepel")
    
    
    df <- structure(list(long_lbl = c("chevrolet, k1500 tahoe 4wd, auto(l4)", 
                                      "chevrolet, k1500 tahoe 4wd, auto(l4)", "subaru, forester awd, manual(m5)", 
                                      "subaru, forester awd, manual(m5)", "toyota, camry, manual(m5)", 
                                      "toyota, camry, manual(m5)", "toyota, toyota tacoma 4wd, manual(m5)", 
                                      "toyota, toyota tacoma 4wd, manual(m5)", "volkswagen, jetta, manual(m5)", 
                                      "volkswagen, jetta, manual(m5)"), year = c(1999L, 2008L, 1999L, 
                                                                                 2008L, 1999L, 2008L, 1999L, 2008L, 1999L, 2008L), mean_cty = c(11, 
                                                                                                                                                14, 18, 20, 21, 21, 15, 17, 33, 21)), class = c("tbl_df", "tbl", 
                                                                                                                                                                                                "data.frame"), row.names = c(NA, -10L))
    
    df_wrap <- df %>%  
      mutate(wrap_lbl = stringr::str_wrap(long_lbl, width = 25))
    
    # With geom_text_repel
    ggplot(df_wrap, aes(x = year, y = mean_cty, group = long_lbl)) +
      geom_line() +
      geom_text_repel(aes(label = wrap_lbl),
                      hjust = "outward",
                      direction = "y",
                      seed = 57,
                      min.segment.length = 100) +
      scale_x_continuous(expand = expansion(add = 10))
    
    # With geom_label_repel
    ggplot(df_wrap, aes(x = year, y = mean_cty, group = long_lbl)) +
      geom_line() +
      geom_label_repel(aes(label = wrap_lbl),
                      hjust = "outward",
                      direction = "y",
                      seed = 57,
                      min.segment.length = 100) +
      scale_x_continuous(expand = expansion(add = 10))
    

提交回复
热议问题