0

I'm trying to add some percent labels to a pie chart but any of the solutions works. The thing is that the chart displays the number of tasks completed grouped by category.

 output$plot2<-renderPlot({
ggplot(data=data[data$status=='100% completed',], aes(x=factor(1), fill=category))+
  geom_bar(width = 1)+
  coord_polar("y")

enter image description here

ytu
  • 1,822
  • 3
  • 19
  • 42
greennyyy
  • 31
  • 1
  • 1
  • 7
  • This could be related: https://stackoverflow.com/questions/47238098/plotting-pie-charts-in-ggplot2/47238534#47238534 – www Feb 18 '18 at 12:40

1 Answers1

2

Using geom_text with position_stack to adjust the label locations would work.

library(ggplot2)
library(dplyr)

# Create a data frame which is able to replicate your plot
plot_frame <- data.frame(category = c("A", "B", "B", "C"))

# Get counts of categories
plot_frame <- plot_frame %>%
  group_by(category) %>%
  summarise(counts = n()) %>%
  mutate(percentages = counts/sum(counts)*100)

# Plot
ggplot(plot_frame, aes(x = factor(1), y = counts)) +
  geom_col(aes(fill = category), width = 1) +
  geom_text(aes(label = percentages), position = position_stack(vjust = 0.5)) +
  coord_polar("y")

The codes above generate this:

Pie charts with percentages

You might want to change the y-axis from counts to percentages since you are labeling the latter. In that case, change the values passed to ggplot accordingly.

ytu
  • 1,822
  • 3
  • 19
  • 42