0

I have a question about a possibility to specifying a layout of pie chart. Let's take the code following

pie_chart=function(vec,save){
      if (class(vec)=='numeric'){vec<-as.character(vec)
      vec<-print(paste('var',vec))
      }
      df<-data.frame(table(vec))
      colnames(df)[1]<-'group'
      bp<- ggplot(df, aes(x="", y=Freq, fill=group))+
        geom_bar(width = 1, stat = "identity")
      blank_theme <- theme_minimal()+
        theme(
          axis.title.x = element_blank(),
          axis.title.y = element_blank(),
          panel.border = element_blank(),
          panel.grid=element_blank(),
          axis.ticks = element_blank(),
          plot.title=element_text(size=14, face="bold")
        )
      
      pie <- bp + coord_polar("y", start=0)
      pie + scale_fill_brewer("Characteristic") + blank_theme +
        theme(axis.text.x=element_blank())+
        geom_text(aes(y = Freq/3 + c(0, cumsum(Freq)[-length(Freq)]), 
                      label = print(paste0(Freq,'(',percent(Freq/(sum(Freq))),')'))), size=5)
    }
    pie_chart(c(rep(1,50),rep(2,60),rep(3,26),rep(4,24)))

enter image description here

And as you can see at the picture above, labels are placed in weird way. Is there any easy way how can I center them into a 'middle of part of the pie' ?

Thanks in advance !

John
  • 1,849
  • 2
  • 13
  • 23
  • 1
    Hello, your problem will make more sense to you if you inactivate the polar coordinates: the y positions of the labels are wrong (which is not big news for you I suppose). This post contains the solution to your problem: https://stackoverflow.com/questions/6644997/showing-data-values-on-stacked-bar-chart-in-ggplot2. – Vincent Guillemot Aug 10 '20 at 11:36

1 Answers1

3

Change your geom_text(aes) for y to:

geom_text(aes(y = rev(Freq)/2 + c(0, cumsum(rev(Freq))[-length(Freq)]),
          label = print(paste0(rev(Freq),'(',percent(rev(Freq)/(sum(Freq))),')'))), size=5)

Based on Vincent's comment, I removed the polar coordinates. I was able to see that your Freq values were in the reverse order, so their relative spacing was correct, but their absolute position was wrong. Note, I simplified the label for clarity.

enter image description here

To get them in the right place, I first used rev() to reverse the Freq in the calculation. This put the labels in approximately the correct place, but still in the wrong order:

enter image description here

Then, I used rev in the label aesthetic, and now everything is good. I also divided by 2 instead of 3 to center the labels in the blocks.

enter image description here

Finally, putting polar coordinates back in, we get:

enter image description here

Ben Norris
  • 5,639
  • 2
  • 6
  • 15