删除使用plotmath制作的ggrepel标签之间的空间

时间:2018-11-18 04:53:55

标签: r ggplot2 plotmath ggrepel

我正在创建一个要在其中使用ggrepel显示标签的图。我在下面显示一个最小的示例,该示例说明标签如何具有两个用逗号分隔的成分-首先与鸢尾花种类的类型有关,其次与该组的样本量有关。

# needed libraries
set.seed(123)
library(ggrepel)

# creating a dataframe with label column
(df <- iris %>%
  dplyr::group_by(Species) %>%
  dplyr::summarise(n = n(), mean = mean(Sepal.Length)) %>%
  purrrlyr::by_row(
    .d = .,
    ..f = ~ paste("list(~",
                  .$Species,
                  ",",
                  .$n,
                  ")",
                  sep = ""),
    .collate = "rows",
    .to = "label",
    .labels = TRUE
  ))
#> # A tibble: 3 x 4
#>   Species        n  mean label               
#>   <fct>      <int> <dbl> <chr>               
#> 1 setosa        50  5.01 list(~setosa,50)    
#> 2 versicolor    50  5.94 list(~versicolor,50)
#> 3 virginica     50  6.59 list(~virginica,50)

# displaying labels
ggplot(iris, aes(Species, Sepal.Length)) +
  geom_point() +
  ggrepel::geom_label_repel(data = df,
                            aes(x = Species, y = mean, label = label),
                            parse = TRUE)

reprex package(v0.2.1)于2018-11-17创建

我的问题是如何摆脱这两个组件之间的空间。尽管我在sep = ""函数中指定了paste(),但是在两个我不想要的组件之间仍然有多余的空间(例如setosa, 50versicolor, 50,{{1} }标签应改为virginica, 50setosa,50versicolor,50)。

1 个答案:

答案 0 :(得分:2)

下面是代码的更新版本,该代码实现了一种在种类名称和样本数量之间放置逗号(无后续空格)的方法。例如,您标记的标签看起来像"~setosa*\",\"*50"而不是list(~setosa,50)

(df <- iris %>%
    dplyr::group_by(Species) %>%
    dplyr::summarise(n = n(), mean = mean(Sepal.Length)) %>%
    purrrlyr::by_row(
      .d = .,
      ..f = ~ paste("~",
                    .$Species,
                    "*\",\"*",
                    .$n,
                    "",
                    sep = ""),
      .collate = "rows",
      .to = "label",
      .labels = TRUE
    ))
#> # A tibble: 3 x 4
#>   Species        n  mean label               
#>   <fct>      <int> <dbl> <chr>               
#> 1 setosa        50  5.01 "~setosa*\",\"*50"
#> 2 versicolor    50  5.94 "~versicolor*\",\"*50"
#> 3 virginica     50  6.59 "~virginica*\",\"*50"


# displaying labels
ggplot(iris, aes(Species, Sepal.Length)) +
  geom_point() +
  stat_smooth(method="lm",size=0.6,se=FALSE,colour="black")+
  ggrepel::geom_label_repel(data = df,
                            aes(x = Species, y = mean, label = label),
                            parse = TRUE)

会产生以下情节:

Plot with labels without spaces

希望有帮助。