【问题标题】:customizing label positions in a pie chart using `ggplot2`使用“ggplot2”自定义饼图中的标签位置
【发布时间】:2026-01-20 10:20:03
【问题描述】:

问题

我正在尝试创建一个通用函数来使用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 facet,标签是重叠的,我想找到一个通用解决方案来解决如何扰动标签的径向位置以使它们重叠最少。

如何做到这一点?

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

【问题讨论】:

    标签: r ggplot2 pie-chart


    【解决方案1】:

    您可以尝试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")
    

    【讨论】: