目录
数据格式
普通绘图
添加比例
R语言 堆砌图_r语言堆砌图-CSDN博客
关键点在于数据转换步骤和数据比例计算步骤,然后个性化调整图。
①data <- melt(dat, id.vars = c("ID"))##根据分组变为长数据
②#计算百分比##
data2 <- ddply(data,
"ID", ##需展示的X轴列名
transform,
percent = value / sum(value) * 100)#相当于按照样本分组,然后计算比例
#只提取需要的行
data2a <- data2[data2$variable=="high",]
data2a$percent <- round(data2a$percent,3)
数据格式
rm(list = ls())
library(ggplot2)
library(tidyverse)
library(reshape)
library(plyr)
library(patchwork)
dat <- as.data.frame(cbind(1:5, 5:1))
colnames(dat) <- c("high","low")
dat$ID <- paste0("samp",1:nrow(dat))
head(dat)high low ID 1 1 5 samp1 2 2 4 samp2 3 3 3 samp3 4 4 2 samp4 5 5 1 samp5
需要进行数据转换
##数据转换##
data <- melt(dat, id.vars = c("ID"))##根据分组变为长数据
普通绘图
p <- ggplot(data = data,aes(x=ID,y=value,fill=variable))+#geom_bar(stat = "identity",position = "stack")+ ##展示原来数值geom_bar(stat = "identity",position = "fill")+ ##按照比例展示:纵坐标为1scale_y_continuous(expand = expansion(mult=c(0.01,0.1)),##展示纵坐标百分比数值labels = scales::percent_format())+scale_fill_manual(values = c("high"="#98d09d","low"="#e77381"), ##颜色调整limits=c("high","low"))+ ##limit调整图例顺序theme(panel.background = element_blank(), ##主题设置axis.line = element_line(), legend.position = "bottom")+labs(title = "Title",x=NULL,y="percent")+ ##X,Y轴设置guides(fill=guide_legend(title = NULL,nrow = 1,byrow = FALSE))
p
#dev.off()
添加比例
计算百分比
#计算百分比##
data2 <- ddply(data, "ID", ##需展示的X轴列名transform,percent = value / sum(value) * 100)#相当于按照样本分组,然后计算比例
#只提取需要的行
data2a <- data2[data2$variable=="high",]
data2a$percent <- round(data2a$percent,3)
head(data2a)ID variable value percent 1 samp1 high 1 16.667 3 samp2 high 2 33.333 5 samp3 high 3 50.000 7 samp4 high 4 66.667 9 samp5 high 5 83.333
绘图
p1 <- ggplot(data = data,aes(x=ID,y=value,fill=variable))+#geom_bar(stat = "identity",position = "stack")+ ##展示原来数值geom_bar(stat = "identity",position = "fill")+ ##按照比例展示:纵坐标为1scale_y_continuous(expand = expansion(mult=c(0.01,0.1)),##展示纵坐标百分比数值labels = scales::percent_format())+scale_fill_manual(values = c("high"="#98d09d","low"="#e77381"), ##颜色调整limits=c("high","low"))+ ##limit调整图例顺序geom_text(data=data2a,aes(x=ID,y=1,label=paste0(value,"\n",#跨行"(",percent,")")),inherit.aes = FALSE,vjust=-0.2)+theme(panel.background = element_blank(), ##主题设置axis.line = element_line(), legend.position = "bottom")+labs(title = "Title",x=NULL,y="percent")+ ##X,Y轴设置guides(fill=guide_legend(title = NULL,nrow = 1,byrow = FALSE))p1
#dev.off()
合图
p2 <-p+ p1
p2
补充:
跟着Nature学作图:R语言ggplot2堆积柱形图完整示例 - 简书 (jianshu.com)
《R数据可视化手册》——3.8 绘制百分比堆积条形图-阿里云开发者社区 (aliyun.com)