ggplot Donut chart

后端 未结 2 1466
臣服心动
臣服心动 2020-12-07 23:24

Hi I really have googled this a lot without any joy. Would be happy to get a reference to a website if it exists. I\'m struggling to understand the Hadley documentation on p

2条回答
  •  时光说笑
    2020-12-08 00:20

    Just trying to solve question 2 with the same approach from bdemarest's answer. Also using his code as a scaffold. I added some tests to make it more complete but feel free to remove them.

    library(broom)
    library(tidyverse)
    # Create test data.
    dat = data.frame(count=c(10,60,20,50),
                     ring=c("A", "A","B","B"),
                     category=c("C","D","C","D"))
    
    # compute pvalue
    cs.pvalue <- dat %>% spread(value = count,key=category) %>%
      ungroup() %>% select(-ring) %>% 
      chisq.test() %>% tidy()
    cs.pvalue <- dat %>% spread(value = count,key=category) %>% 
      select(-ring) %>%
      fisher.test() %>% tidy() %>% full_join(cs.pvalue)
    
    # compute fractions
    #dat = dat[order(dat$count), ]
    dat %<>% group_by(ring) %>% mutate(fraction = count / sum(count),
                                          ymax = cumsum(fraction),
                                          ymin = c(0,ymax[1:length(ymax)-1]))
    
    
    # Add x limits
    baseNum <- 4
    #numCat <- length(unique(dat$ring))
    dat$xmax <- as.numeric(dat$ring) + baseNum
    dat$xmin = dat$xmax -1
    
    
    # plot
    p2 = ggplot(dat, aes(fill=category,
                         alpha = ring,
                         ymax=ymax, 
                         ymin=ymin, 
                         xmax=xmax, 
                         xmin=xmin)) +
      geom_rect(colour="grey30") +
      coord_polar(theta="y") +
      geom_text(inherit.aes = F,
                x=c(-1,1),
                y=0,
                data = cs.pvalue,aes(label = paste(method,
                                                   "\n",
                                                   format(p.value,
                                                          scientific = T,
                                                          digits = 2))))+
      xlim(c(0, 6)) +
      theme_bw() +
      theme(panel.grid=element_blank()) +
      theme(axis.text=element_blank()) +
      theme(axis.ticks=element_blank(),
            panel.border = element_blank()) +
      labs(title="Customized ring plot") + 
      scale_fill_brewer(palette = "Set1") +
      scale_alpha_discrete(range = c(0.5,0.9))
    
    p2
    

    And the result:

    Imgur

提交回复
热议问题