R语言 带标签的圆环图

dwbf0jvd  于 2023-03-05  发布在  其他
关注(0)|答案(1)|浏览(166)

我想创建一个带标签的圆环图。标签本身应该在图表之外,并通过线条连接到圆环图的相应部分。这是我到目前为止所做的,但我很难创建线条并防止标签重叠。

#数据框

geschlecht <- as.data.frame(tibble(
  gender = as.factor(c("männlich", "weiblich", "nicht-binär", "keine Angabe")),
  count = c(46, 43, 7, 4)
))

#计算百分比

geschlecht <- geschlecht %>% mutate(fraction = count / sum(count),
                    ymax = cumsum(fraction),
                    ymin = c(0, head(ymax, n=-1)),
                    labelPosition = (ymax + ymin)/2,
                    label = paste0(gender,"\n",count, "%"))

#创建圆环图

geschlecht_donut <- ggplot(geschlecht, aes(ymax=ymax, ymin=ymin, xmax=4, xmin=3, fill=gender)) +
  geom_rect() +
  geom_label( x=3.5, aes(y=labelPosition, label=label), size=6) +
  coord_polar(theta="y") +
  xlim(c(2, 4)) +
  
  scale_fill_brewer(palette = "OrRd") +
  theme(legend.position = "none") +
  theme_void() +
  guides(
    fill = "none")

geschlecht_donut

这是当前输出和我想要的输出的图片。
Current Output
Desired Output

x8goxv8g

x8goxv8g1#

一种选择是切换到ggrepel::geom_label_repel,使用x=4将标签放置在边界上,并添加一些微调。我还在连接标签和数据点的线段上添加了一些曲率:

library(ggplot2)
library(ggrepel)

ggplot(geschlecht, aes(fill = gender)) +
  geom_rect(aes(ymax = ymax, ymin = ymin, xmax = 4, xmin = 3)) +
  geom_label_repel(aes(x = 4, y = labelPosition, label = label),
    size = 6, hjust = .5,
    nudge_x = 1, direction = "x",
    segment.curvature = -0.1,
    segment.ncp = 3,
    segment.angle = 20, seed = 123
  ) +
  coord_polar(theta = "y", clip = "off") +
  xlim(c(2, 5)) +
  scale_fill_brewer(palette = "OrRd") +
  theme(legend.position = "none") +
  theme_void() +
  guides(
    fill = "none"
  )

相关问题