1

I am using geom_label_repel but the labels didn't place on the areas correctly this is my data

subject |n |prop

  A     | 9| 22%

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

this my code

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

As you can see they are pointing to wrong areas can you help me please to fix this

enter image description here

Dave2e
  • 22,192
  • 18
  • 42
  • 50
fatima
  • 11
  • 1

1 Answers1

0

Here is a way how it works. Credits to 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()

data:

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

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66