R语言画同心圆环形图(donut chart)展示比例

### load the library
library(dplyr)
library(ggplot2)
options(stringsAsFactors=F)

### construct the dataset
data <- data.frame(Category=c('A','B','C','D'), Freq=c(100,200,300,400))
subdata <- data.frame(SubCategory=c('A_1','A_2','B_1','B_2','B_3','C_1','C_2','D_1'), Freq=c(30,70,100,20,80,50,250,400), Category=c('A','A','B','B','B','C','C','D'))
subdata$Total <- data[match(as.character(subdata$Category), data$Category),'Freq']

### go ahead
subdata <- subdata %>%
    mutate(Tot = sum(Freq)) %>% 
    group_by(Category) %>% 
    mutate(CUM = cumsum(Freq), DomSize = max(CUM))

### calculate the bottom edge of the Domains when stacked
DomBot <- unique(select(subdata, Category, Tot, DomSize)) %>% ungroup() %>% mutate(Bottom = Tot - cumsum(DomSize))

### joining
subdata <- inner_join(subdata, select(DomBot, Category, Bottom))
subdata <- mutate(subdata, Pos = Bottom + CUM - Freq/2)

### plotting
ggplot() + 
    geom_col(aes(x = 2, y = Freq, fill = Category), data = data, color = "black", width = 0.8) + 
    geom_col(aes(x = 3, y = Freq, fill = Category), data = subdata, color = "black", , width = 0.8) + 
    geom_text(aes(label = SubCategory, x= 3, y = Pos), data = subdata, size = 4) +
    xlim(0, 3.5) + 
    labs(x = NULL, y = NULL) + 
    theme(axis.ticks=element_blank(), axis.text=element_blank(), axis.title=element_blank(), panel.background=element_blank(), panel.border=element_blank()) + 
    coord_polar(theta = "y")
dev.off()

show the result:


donut.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容