firmo23
firmo23

Reputation: 8404

Place text label into corresponding slice of pie chart using ggplot2

I have the dataframe below and I create apie chart using ggplot2 but the text labels are not inside the correct slice and some of them overlap one the other. I need also text not to overlap one another.

HU2<-c(1,  2,  4,  5,  7,  8,  9,  10, 11)
Freq<-c(5118, 2226, 5817,  159, 6766,   27,  984,  654,   89)
Abs_Freq<-c("0.23", "0.10", "0.27", "0.01", "0.31", "0.00", "0.05", "0.03", "0.00")
df$label <- scales::percent(as.numeric(df$Abs_Freq))

p2<-ggplot(data=df)+
  geom_bar(aes(x="", y=as.numeric(Abs_Freq), fill=HU2), stat="identity", width = 1)+
  coord_polar("y", start=0)+
  theme_void()+
  geom_text(aes(x=1, y = cumsum(as.numeric(Abs_Freq)) - as.numeric(Abs_Freq)/2, label=label))
p2

enter image description here

Upvotes: 0

Views: 100

Answers (1)

teunbrand
teunbrand

Reputation: 37933

It's often easiest to diagnose pie-chart problems in cartesian space before using polar coordinates. In this case, instead of calculating the cumalitive frequency manually, you can use position = position_stack() to place the text in the right wedge. Note that also the group aesthetic in the text and in the bar should be identical if you want to have the stacking work as intended.

library(ggplot2)

HU2<-c(1,  2,  4,  5,  7,  8,  9,  10, 11)
Freq<-c(5118, 2226, 5817,  159, 6766,   27,  984,  654,   89)
Abs_Freq<-c("0.23", "0.10", "0.27", "0.01", "0.31", "0.00", "0.05", "0.03", "0.00")
df <- data.frame(
  HU2 = HU2,
  Freq = Freq,
  Abs_Freq = Abs_Freq
)

df$label <- scales::percent(as.numeric(df$Abs_Freq))

ggplot(data=df)+
  geom_col(aes(x="", y=as.numeric(Abs_Freq), fill=as.factor(HU2)),
           width = 1)+
  coord_polar("y", start=0)+
  theme_void()+
  geom_text(aes(x=1, y = as.numeric(Abs_Freq), label=label, group = as.factor(HU2)),
            position = position_stack(vjust = 0.5))

Created on 2021-03-27 by the reprex package (v1.0.0)

Upvotes: 1

Related Questions