Home > Mobile >  Create pie chart showing value for only one category and change positioning of the value
Create pie chart showing value for only one category and change positioning of the value

Time:11-29

I would like to create series of pie charts in ggplot2. Each plot is showing percentage of two categories ('Yes', 'No'), but I want to show only 'Yes' percentage values and the value should be centred relatively to whole plot not only the 'Yes' part itself. The problem is that I'm able to change the position of the value locally i.e. within the category slice but not in the context of whole pie chart.

Dataset:

df <- data.frame(Perc = c(78, 94, 99, 22, 6, 1), 
    Source = as.factor(rep(c("Oil", "Solar", "Wind"), 2)),
    Agree = as.factor(c(rep("Yes", 3), rep("No", 3))))

Plotting:

ggplot(df, aes(x=" ", y=Perc, group=rev(Agree), fill=Agree))  
    geom_bar(size = .5, stat = "identity", color = "black")   
    scale_fill_manual(values = c("grey", "lightgreen"))  
    coord_polar("y", start=0)   
    geom_text(aes(label = ifelse(Agree=="Yes", paste0(Perc, "%"),"")))  
    facet_grid(~Source)   theme_void()   theme(legend.position = "none", strip.text.x = element_text(size = 9))

Now I'm getting plot that looks like this:

Pie charts without centralised values

And I would like to create this plot:

Pie charts with centralised values

CodePudding user response:

One option would be to set the y value to 50 for the labels:

library(ggplot2)

ggplot(df, aes(x = " ", y = Perc, group = rev(Agree), fill = Agree))  
  geom_bar(size = .5, stat = "identity", color = "black")  
  scale_fill_manual(values = c("grey", "lightgreen"))  
  coord_polar("y", start = 0)  
  geom_text(aes(y = 50, label = ifelse(Agree == "Yes", paste0(Perc, "%"), "")))  
  facet_grid(~Source)  
  theme_void()  
  theme(legend.position = "none", strip.text.x = element_text(size = 9))

enter image description here

  • Related