I am hoping to label my pie charts with the percentage value. However, when I try to do that, it causes my pie charts to shrink.
This is the original code without the labels:
shortlistpied <- reactive({
shortlistpie %>%
group_by_(input$y, input$x) %>%
summarize(Percentage = n()) %>%
group_by_(input$x) %>%
mutate(Percentage = Percentage / sum(Percentage) * 100) %>%
arrange_(input$x)
})
output$plot2 <- renderPlot({
if (input$type == "Pie Chart") {
ggplot(shortlistpied(), aes_string(x = factor(1), y = "Percentage", fill = input$y)) +
geom_bar(stat = "identity", width = 1, position = position_fill()) +
coord_polar("y") +
facet_wrap( ~get(input$x)) +
theme_void()
} else NULL
})
and this is what it produces:
This is the code with the labels:
shortlistpied <- reactive({
shortlistpie %>%
group_by_(input$y, input$x) %>%
summarize(Percentage = n()) %>%
group_by_(input$x) %>%
mutate(Percentage = Percentage / sum(Percentage) * 100) %>%
arrange_(input$x) %>%
mutate(label_pos = cumsum(Percentage) - Percentage / 2,
perc_text = paste0(round(Percentage), "%"))
})
output$plot2 <- renderPlot({
if (input$type == "Pie Chart") {
ggplot(shortlistpied(), aes_string(x = factor(1), y = "Percentage", fill = input$y)) +
geom_bar(stat = "identity", width = 1, position = position_fill()) +
geom_text(aes(x = 1.25, y = label_pos, label = perc_text), size = 4) +
coord_polar("y") +
facet_wrap( ~get(input$x)) +
theme_void()
} else NULL
})
and this is what it produces:
For reference, input$x
refers to Gender and input$y
refers to Education in this case.
Thank you so much for all of your help!