R Shiny: Pie chart shrinks after labeling

☆樱花仙子☆ 提交于 2019-12-13 06:27:29

问题


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!

来源:https://stackoverflow.com/questions/53643299/r-shiny-pie-chart-shrinks-after-labeling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!