使用 ggplot2 自定义饼图中的标签位置

customizing label positions in a pie chart using `ggplot2`

问题

我正在尝试创建一个通用函数来使用 ggplot2 绘制 标记的 饼图。我所写的内容在 大多数情况下 有效。它表现不佳的环境是当比例很小时(见下图)。所以我想以最小化重叠的方式自定义标签沿径向轴的位置。请注意,我可以硬编码标签的位置值,使其适用于 this 图,但我想选择一种更通用的策略。

数据

# setup
set.seed(123)
library(ggplot2)

# for reproducibility
df <-
  structure(list(
    epoch = structure(c(1L, 2L, 1L, 2L, 1L, 2L, 1L, 2L),
      .Label = c("Before", "After"),
      class = "factor"
    ),
    mode = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 4L, 4L),
      .Label = c("A", "P", "C", "T"), class = "factor"
    ),
    counts = c(30916L, 21117L, 7676L, 1962L, 1663L, 462L, 7221L,
               197L),
    perc = c(
      65.1192181312663,
      88.9586317297161,
      16.1681691802174,
      8.26522874715646,
      3.50282247872609,
      1.94624652455978,
      15.2097902097902,
      0.829892998567697
    ),
    label = c("65%", "89%", "16%", "8%",
              "4%", "2%", "15%", "1%")
  ),
  row.names = c(NA, -8L),
  class = c("tbl_df",
            "tbl", "data.frame")
  )

情节

请注意,对于 After 方面,标签是重叠的,我想找到一个通用的解决方案,以解决如何扰乱标签的径向位置以使它们重叠最少的问题。

如何做到这一点?

ggplot2::ggplot(data = df, mapping = ggplot2::aes(x = "", y = perc)) +
  ggplot2::geom_col(
    mapping = ggplot2::aes(fill = mode),
    position = "fill",
    color = "black",
    width = 1,
    na.rm = TRUE
  ) + # adding label with percentages and/or counts
  rlang::exec(
    .fn = ggplot2::geom_label,
    mapping = ggplot2::aes(label = label, group = mode),
    position = ggplot2::position_fill(vjust = 0.5),
    show.legend = FALSE,
    na.rm = TRUE
  ) +
  ggplot2::facet_wrap(facets = ~epoch) +
  ggplot2::coord_polar(theta = "y")

您可以尝试 ggrepel 包中的 geom_label_repel。只需确保将方向参数设置为“y”:

ggplot2::ggplot(data = df, mapping = ggplot2::aes(x = "", y = perc)) +
  ggplot2::geom_col(
    mapping = ggplot2::aes(fill = mode),
    position = "fill",
    color = "black",
    width = 1,
    na.rm = TRUE
  ) + # adding label with percentages and/or counts
  rlang::exec(
    .fn = ggrepel::geom_label_repel,
    mapping = ggplot2::aes(label = label, group = mode),
    position = ggplot2::position_fill(vjust = 0.5), direction = "y",
    show.legend = FALSE,
    na.rm = TRUE
  ) +
  ggplot2::facet_wrap(facets = ~epoch) +
  ggplot2::coord_polar(theta = "y")