Search code examples
rggplot2ggrepel

Labels of piechart incorrectly shown in ggplot2


I'm trying to piechart my DATA below, but the labels and colors seem to be misplaced.

Is there any specific setting to align the labels and colors?

library(ggrepel)

DATA <- read.table(header=T, text="
EthnicCd    SchoolYear n_RCA percent  csum    pos
Hispanic          2324  4520 50%      9117   6857  
Asian             2324  1800 20%      4597   3697  
White             2324  1737 19%      2797   1928. 
Black             2324   447 5%       1060   836. 
Pacific           2324   395 4%        613   416. 
Multiracial       2324   203 2%        218   116. 
AmerInd           2324    15 0%         15   7.5")


ggplot(DATA, aes(x="", y=n_RCA, fill=EthnicCd)) +
  geom_bar(stat="identity", width=.008, color="white") +
  coord_polar("y", start = 5.5) +
  theme_void() +
  scale_fill_brewer(palette="Set1")+
  guides(fill = guide_legend(title = bquote(~bold("Ethnic Background"))))+
  geom_label_repel(aes(y = pos, label = paste0(n_RCA,"\n(",percent,")")),
                   size = 3, nudge_x = .004, nudge_y=4,
                   show.legend = FALSE)

Solution

  • First of all, you are providing different y values for the two layers. Secondly, the bars are stacked by default, but the labels are not. We need to provide a position to the labels to match the stacking of the bars, and we can use the justification parameter to place the labels halfway the bars:

    ggplot(DATA, aes(x = 1, n_RCA, fill=EthnicCd)) +
      geom_col(width = 1, color="white") +
      geom_label_repel(
        aes(x = 1.49, label = paste0(n_RCA,"\n(",percent,")")),
        position = position_stack(vjust = 0.5),
        size = 3,
        show.legend = FALSE
      ) +
      coord_polar("y", start = 5.5) +
      theme_void() +
      scale_fill_brewer(palette="Set1")+
      guides(fill = guide_legend(title = bquote(~bold("Ethnic Background"))))
    

    I set the x-positions to ~1.5 for the labels, so that they are placed on the outside of the pie. This is because I set x = 1 for the bars, and a bar "width" of 1, so that it ranges from 0.5 to 1.5.

    Polar coordinates can be confusing sometimes, it often helps to plot in Cartesian coordinates first, so that e.g. the stacking problem becomes more obvious.

    enter image description here