ggplot2绘制饼图的基本理论就是用极坐标系展示堆积柱形图
堆积柱形图的画法有两种,一种是用geom_col,另一种是geom_tile函数。笔者感觉画饼图时,用geom_tile会好看一些。
本文使用蛋白质磷酸化位点类型的数据,蛋白质磷酸化常见位点包括S(丝氨酸),Y(酪氨酸),T(苏氨酸)三种。
使用geom_col绘图:
首先导入数据:
pho <- read.csv(file = "clipboard",header = T,sep = "\t")
pho
y <- table(pho$Amino.acid) %>% as.data.frame() %>% cbind(z = rep(1,3),prop = prop.table(y$Freq))
y <- cbind(y,axis_y = c(90*y$prop[1]+180*y$prop[2]+180*y$prop[3],90*y$prop[2]+180*y$prop[3],90*y$prop[3]),axis_x = rep(1.4,3)) #计算每个标签的纵坐标,方便画图时使用,就是计算每个扇形的角度一半的位置(就是扇形的中线),此时标签是居中的(可是并不是很居中)
y$Var2 <- paste(y$Var1,"(",y$prop*100,"%)",sep = "")
y #axis_x是极坐标中在x轴上的位置,可以自己设定合适的位置
ggplot(y)+
geom_segment(aes(x = axis_x-0.05,y = axis_y,xend = axis_x+0.2,yend = axis_y,alpha = 0.8),
color = c("red","green","yellow"),size = 1.5)+
geom_col(aes(z,Freq,fill = Var1,alpha = 0.8),color = "black",size = 2)+
geom_point(aes(x = axis_x+0.2,y = axis_y),size = 2,color = c("red","green","yellow"))+
coord_polar(theta = "y")+
scale_fill_manual(values = c("red","green","yellow"),guide = NULL)+
geom_text(aes(x = axis_x+0.3,y = axis_y,label = Var2),size = 7,adj = 0.5)+
scale_alpha(guide = NULL)+
theme(panel.background = element_blank(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
plot.title = element_blank())
最终图片:
使用geom_tile绘图:
(
geom_tile函数可以设置每个方块的高度,达到和堆积柱形图一样的效果
)
同样先导入数据:
pho <- read.csv(file = "clipboard",header = T,sep = "\t")
y <- table(pho$Amino.acid) %>% as.data.frame() %>% cbind(z = rep(1,3),prop = prop.table(y$Freq))
y <- cbind(y,axis_y = c(y$prop[1]/2+y$prop[2]+y$prop[3],y$prop[2]/2+y$prop[3],y$prop[3]/2),axis_x = rep(1.4,3))
#计算每个方块的中点位置
y$Var2 <- paste(y$Var1,"(",y$prop*100,"%)",sep = "")
y
开始绘图:
ggplot(y)+
geom_segment(aes(x = axis_x,y = axis_y,xend = axis_x+0.2,yend = axis_y,alpha = 0.8),
color = c("red","green","yellow"),size = 1.5)+
geom_tile(aes(z,axis_y,fill = Var1,alpha = 0.8,height = prop),color = "black",size = 2)+ # 设置中点为纵坐标,将比例设置为方块的高度,就可以达到堆积柱形图的效果
geom_point(aes(x = axis_x+0.2,y = axis_y),size = 2,color = c("red","green","yellow"))+
coord_polar(theta = "y")+
scale_fill_manual(values = c("red","green","yellow"),guide = NULL)+
geom_text(aes(x = axis_x+0.3,y = axis_y,label = Var2),size = 7,adj = 0.5)+
scale_alpha(guide = NULL)+
theme(panel.background = element_blank(),
axis.line.x = element_blank(),
axis.line.y = element_blank(),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks.x = element_blank(),
axis.ticks.y = element_blank(),
plot.title = element_blank())