代码之家  ›  专栏  ›  技术社区  ›  jerH

ggplot2饼和甜甜圈在同一个图上,只有摘要数据

  •  0
  • jerH  · 技术社区  · 5 年前

    here

    enter image description here

    对于组织,我知道:

    Telework rate: 33%
    No telework rate: 67%
    

    Very infrequently: 19.8%
    1-2 days/month: 4.8%
    1-2 days/week: 7.9%
    3-4 days/week: 0.4%
    Every work day: 0.1%
    

    对于那些没有远程工作的人,他们的理由是:

    Must be physically present: 11.5%
    Technical limitations: 7.1%
    Not authorized: 25.5%
    Choose not to: 23.9%
    

    我希望中间的饼图显示给定组织的远程工作/无远程工作突破,外部甜甜圈显示频率/原因。但我不知道该怎么做,因为我发现的每个例子都是从个人的反应开始的。

    0 回复  |  直到 5 年前
        1
  •  2
  •   Jonathan V. Solórzano    5 年前

    这里有一个解决方案,可能非常接近您正在寻找的。

    我使用了一些类似于你展示的数据:

    df<-data.frame(Org=c("Tele",rep(c("Tele","NotTele"),each=4)),
                         CatFreq = LETTERS[1:9],
                   Freq = c(19.8,4.8,7.9,0.4,0.1,11.5,7.1,25.5,22.9))
    

    library(tidyverse)
    
    df %>%
      #Calculate cumulative sums
      mutate(cumsum = cumsum(Freq),
             min = cumsum-Freq) %>%
      #Calculate cumulative sums by Org
      group_by(Org) %>%
      mutate(cumsum2 = max(cumsum(Freq))) %>%
      ungroup() %>%
      #Get mid point to print labels for Org levels
      mutate(mid = ifelse(Org == "Tele", cumsum2 / 2, min(cumsum2) + (max(cumsum2)/2) ) ) %>%
      #Do the ggplot by doing two geom_rect, 1 for Org, 1 for CatFreq
      ggplot()+
      geom_rect(aes(xmin = 1,
                    xmax = 2,
                    ymin = min, 
                    ymax = cumsum,
                    fill = Org))+
      #Add labels for Org
      geom_text(aes(x = 1 + ((2 - 1)/2), 
                    y = mid,
                    label = paste(Org, paste0(cumsum2, "%"), sep= "\n"))) +
      geom_rect(aes(xmin = 2,
                    xmax = 3,
                    ymin = min, 
                    ymax = cumsum,
                    fill = CatFreq))+
      #Add labels for CatFreq
      geom_text(aes(x = 2 + ((3 - 2)/2), 
                    y = min + ((cumsum - min)/2),
                    label = paste(CatFreq, paste0(Freq, " %"), sep= "\n"))) +
      #Changing the plot to pie
      coord_polar("y", start = 0) +
      #Making it a doughnut
      xlim(c(0,4)) + 
      #Set theme void
      theme_void() +
      #Eliminate legend
      theme(legend.position = "none")
    

    enter image description here