其他
ggplot2优雅的绘制车轱辘图
欢迎关注R语言数据分析指南
❝之前在一篇论文里面看到一张特殊的组合饼图感觉很不错,下面来构建数据进行复现,来看具体案例
❞
加载R包
library(tidyverse)
library(scales)
library(ggtext)
library(patchwork)
library(cowplot)
library(RColorBrewer)
定义颜色
mycolors <- colorRampPalette(brewer.pal(12,"Paired"))(21)
构建数据集
df <- tribble(~group,~value,
"A", 40,
"B",60)
Figure-1
p1 <- df %>% arrange(desc(value)) %>%
ggplot(.,aes(x="",y=value,fill=group))+
geom_bar(width=1,stat="identity")+
coord_polar("y",start=0)+
geom_text(aes(y = value/2 + c(0, cumsum(value)[-length(value)]),
label = percent(value/100)), size=4)+
scale_fill_manual(values = mycolors)+
theme(axis.text.x=element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank(),
panel.background = element_blank(),
legend.position = "none",
legend.title = element_blank(),
legend.text = element_text(color="black",size=9),
legend.spacing.x=unit(0.1,'cm'),
legend.key.width=unit(0.5,'cm'),
legend.key.height=unit(0.5,'cm'),
legend.background=element_blank())
数据清洗
df2 <- read_tsv("otu_taxa_table.xls") %>%
select(OTU:C5,taxonomy) %>%
separate(taxonomy,
into=c("domain","phylum","class","order","family","genus","species"),sep=";") %>%
mutate_at(vars(c(`domain`:`species`)),~str_split(.,"__",simplify=TRUE)[,2]) %>%
select(A1:C5,genus) %>% drop_na() %>%
group_by(genus) %>% filter(genus !="") %>%
count() %>% ungroup() %>% mutate(value=n/sum(n)) %>% arrange(desc(value)) %>%
mutate(group=case_when(value < 0.0088999644 ~ "others",
TRUE ~ as.character(genus))) %>%
group_by(group) %>% summarise(value=sum(value)) %>% arrange(desc(value))
df2$group <- factor(df2$group,levels = df2$group)
Figure-2
p2 <- df2 %>% ggplot(.,aes(x="",y=value,fill=group))+
geom_bar(width=1,stat="identity")+
coord_polar("y",start=0)+
scale_fill_manual(values = mycolors)+
theme(axis.text.x=element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
panel.border = element_blank(),
panel.grid=element_blank(),
axis.ticks = element_blank(),
panel.background = element_blank(),
legend.position = "none",
legend.title = element_blank(),
plot.margin=unit(c(0,13,0,0),units="cm"),
legend.text = element_text(color="black",size=9),
legend.spacing.x=unit(0.1,'cm'),
legend.key.width=unit(0.5,'cm'),
legend.key.height=unit(0.5,'cm'),
legend.background=element_blank())
拼图
p2 %>% ggdraw()+draw_plot(p1,scale=0.4,x=0.38,y=0)
数据获取
❝本节内容到此结束,喜欢的小伙伴欢迎转发此文档附上一句话到朋友圈「30分钟后后台截图给我」,即可获取对应的数据及代码,如未及时回复可添加我的微信,也可打赏文档获取代码;如果您非常喜欢我的内容,「欢迎添加小编微信加入我的VIP交流群」,群内会同步上传文档代码,期待您的加入
❞
欢迎大家扫描下方二维码「QQ交流群」,与全国各地上千位小伙伴交流
小编微信
「关注下方公众号下回更新不迷路」,如需要加入微信交流群可添加小编微信,请备注单位+方向+姓名
往期推荐