无法在饼图中使用 (geom__label_repel) 正确放置标签

问题描述

我正在使用 geom_label_repel 但标签没有正确放置在这些区域这是我的数据

subject |n |prop

  A     | 9| 22%

  B     |10|24% 
 
  C     |12|29% 
  
  D     |10|24%

这是我的代码

df=df %>%
  arrange(desc(subject)) %>%
  mutate(prop = percent(n/41)) -> df 

pie <- ggplot(df,aes(x = "",y = n,fill = fct_inorder(subject))) +
  geom_bar(width = 1,stat = "identity")+
  coord_polar("y",start = 0) +
  geom_label_repel(aes(label =paste0(prop) ),size=5,show.legend=F,nudge_x =-3,nudge_y=32,segment.size=0.5,direction ="both",hjust="inward",vjust="inward")+
guides(fill = guide_legend(title="elective course"))
  theme_void()
pie

正如你所看到的,它们指向了错误的区域,你能帮我解决这个问题吗

enter image description here

解决方法

这是一种工作方式。归功于Unexpected behaviour in ggplot2 pie chart labeling

library(tidyverse)
library(ggrepel)
df <- df %>%
  arrange(desc(subject)) %>%
  mutate(lab.ypos = cumsum(prop) - prop/2)

df2 <- df %>% 
  mutate(
    cs = rev(cumsum(rev(prop))),pos = prop/2 + lead(cs,1),pos = if_else(is.na(pos),prop/2,pos))

ggplot(data = df,aes(x = "",y = prop,fill= fct_inorder(subject)))+ 
  geom_col(width=1) +
  coord_polar(theta = "y",start = 0) +
  geom_label_repel(aes(y = pos,label = paste0(prop,"%")),data = df2,size=4,show.legend = F,nudge_x = 1) +
  guides(fill = guide_legend(title = "Status")) +
  theme_void()

数据:

df <- structure(list(subject = c("A","B","C","D"),n = c(9,12,10),prop = c(22,24,29,24)),row.names = c(NA,-4L),class = c("tbl_df","tbl","data.frame"))

enter image description here