生物信息学与算法生物信息学习生物信息编程

R与python实现圆环图 (ggplot2&matplotli

2019-12-16  本文已影响0人  生信编程日常

​圆环图与饼图类似,也是反映各个部分的占比情况,看各种类型的数据与整体之间的关系。下面将展示一下在R与python中的实现方法。

  1. R的实现 (ggplot2)

R中是没有封装好的包来直接实现的,我们将用ggplot2中的geom_bar进行极坐标变换得到。首先创建两组数:

data1 <- data.frame("cell1" = c(30,25, 66, 13, 23)/sum(c(30,25, 66, 13, 23)), 'type' = c('Intron', 'Intergenic',"UTR","Exon","CDS"))
data2 <- data.frame("cell2" = c(29, 28, 90, 19, 31)/sum(c(29, 28, 90, 19, 31)), "type" = c('Intron', 'Intergenic',"UTR","Exon","CDS"))

然后画出这两组数的barplot:

library(ggplot2)
theme_set(theme_bw())
p <- ggplot() + geom_bar(data1, mapping = aes(x = 0.8, y = cell1, fill = type), color = "gray", stat = 'identity', width = 0.4) + geom_bar(data2, mapping = aes(x = 0.5, y = cell2, fill = type), color = 'gray',width = 0.3, stat = 'identity') + labs(y = 'cells', y = 'percentage')  
p
image

经过极坐标变化可以得到:

p + coord_polar(theta='y')
image

现在还是不太好看,最后把xy轴的刻度和xy轴的的标题去掉:

p  + theme(axis.title.x=element_blank(), axis.title.y=element_blank(), panel.border=element_blank(), panel.grid=element_blank(), axis.ticks = element_blank(), axis.text = element_blank()) + guides(fill = guide_legend(title = 'type'))
image

2. python的实现 (matplotlib.pyplot)

python将用matplotlib中的pyplot画出两个pie图来实现。

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
mpl.rcParams['font.size'] = 7.0 # matplotlib设置全局字体
​
# 创建两组数据
x1 = [30,25, 66, 13, 23]
x2 = [29, 28, 90, 19, 31]
​
x_0 = [1,0,0,0] #用于显示空心
 
​labels = ["Intron","Intergenic","UTR","Exon","CDS"] # 标签
colors = ["#FFDD55","#EE7700","#99FF99","#5599FF","#FF77FF"] # 对应的颜色
​
# 用于设置legend的字体和大小
font1 = {'family' : 'Times New Roman',
'weight' : 'normal',
'size'   : 10,
        }
# 创建图片        
plt.figure(figsize=(8,8))
fig, ax = plt.subplots()
​
#做出三个pie图,最后一个用作中间的空心
pie_1 = ax.pie(x1,startangle = 90,radius=1.8,pctdistance = 0.9,colors=colors)
pie_2 = ax.pie(x2,startangle = 90,radius=1.5,pctdistance = 0.9,colors=colors)
pie_0 = ax.pie(x_0, radius=1.2,colors = 'w')
​
# 设置图片标题
ax.text(0.1, 2.1, 'test', fontsize=18, style='oblique', ha='center',va='top',wrap=True)
​
# 画出每个pie图的边的颜色
for pie_wedge in pie_1[0]:
    pie_wedge.set_edgecolor('gray')
for pie_wedge in pie_2[0]:
    pie_wedge.set_edgecolor('gray')
    
# 设置legend的位置和字体
ax.legend(labels, bbox_to_anchor=(1.3,1.0), loc='center left', prop=font1)
​
# 将图设置为圆形
ax.set(aspect="equal")
最后可以得到: image
上一篇下一篇

猜你喜欢

热点阅读