R发光:标记后饼图缩小

时间:2018-12-06 01:28:27

标签: r ggplot2 shiny pie-chart

我希望将百分比值标记为饼图。但是,当我尝试这样做时,会导致饼图缩小。

这是没有标签的原始代码:

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 
})

这就是它产生的:

original pie charts

这是带有标签的代码:

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 
})

这就是它产生的:

pie charts with labels

在这种情况下,input$x指性别,input$y指教育。

非常感谢您的所有帮助!

0 个答案:

没有答案