利用ggplot2绘制多角图绘制
今天利用ggplot2来进行多角图的绘制,代码如下:
1. 安装需要的R包
install.packages(“ggplot2”)
2. 导入需要的R包
library(ggplot2)
3. 示例代码
raw.data <- read.table(“group.txt”, header = T, stringsAsFactors = T)
# 记录末列的名称
txt <- colnames(raw.data)[ncol(raw.data)]
## 计算坐标轴角度
sides <- ncol(raw.data) - 1 # 边的个数(列数减1,因为有末列)
start_angle <- 90 # 开始角度
basis <- t(sapply((1:sides)-1, function(i){
c(cos(2 * i * pi / sides + start_angle * pi / 180),
sin(2 * i * pi / sides + start_angle * pi / 180))
}))
## 将12维的数据坐标投射到二维
data <- as.matrix(raw.data[, -match(txt, colnames(raw.data))]) %*% basis
# 准备绘图数据
### 点的数据
plot.data <- data.frame(
"x" = data[, 1],
"y" = data[, 2],
"Group" = raw.data$celltype
)
### 多边形的数据
basis <- data.frame(
"x" = basis[, 1],
"y" = basis[, 2]
)
### 类图例的数据
label <- data.frame(
"x" = 1.1 * basis[, 1],
"y" = 1.1 * basis[, 2],
"label" = colnames(raw.data)[-ncol(raw.data)]
)
### 设定颜色(使用的是RGB颜色)
color.palette <- list(
'hEndo'= c(190, 10, 10),'hPeric'= c(225, 160, 30),'hMgl'= c(217, 245, 7),
'hDA1'= c(170, 180, 170),'hDA2'= c(130, 140, 140),'hNbM'= c(180, 140, 130),
'hNbML1'= c(100, 100, 240),'hProgM'= c( 80, 235, 255),'hProgFPM'=c(190, 235, 255),
'hProgFPL'=c(210, 255, 215),'hProgBP'=c(230, 140, 120),'hNProg'= c(255, 195, 28),
'hNbML5'= c(139, 101, 100),'hRgl1'= c(252, 183, 26),'hRgl3'= c(214, 194, 39),
'hRgl2c'= c(255, 120, 155),'hRgl2b'= c(250, 145, 45),'hRgl2a'= c(250, 125, 25),
'hDA0'= c(190, 200, 190),'hOPC'= c(255, 35, 155),'hRN'= c(199, 121, 41),
'hNbGaba'= c( 40, 55, 130),'hGaba'= c( 7, 121, 61),'hOMTN'= c( 95, 186, 70),
'hSert'= c( 50, 180, 180),'eSCa'= c(245, 205, 170),'eSCb'= c(205, 245, 170),
'eSCc'= c(205, 205, 220)
)
color.palette <- lapply(color.palette, function(x){
rgb(red = x[1]/255, green = x[2]/255, blue = x[3]/255)
})
color.palette <- unlist(color.palette) # 最终的颜色格式为一个带名称的16进制字符串
###开始绘图
ggplot(plot.data, aes(x = x, y = y)) +
geom_point(aes(col = Group, size = .5)) +
geom_polygon(mapping = aes(x = x, y = y), data = basis,
fill = "transparent", color = "black", size = 1) +
geom_text(mapping = aes(x = x, y = y, label = label), data = label) +
scale_color_manual(values = color.palette) +
theme_classic() +
theme(axis.line = element_blank(),
axis.title = element_blank(),
axis.ticks = element_blank(),
axis.text = element_blank())
ggsave("wheelplot.pdf", width = 10, height = 8) # 保存图形
代码合集
生信人R语言学习必备
立刻拥有一个Rstudio账号
开启升级模式吧
(56线程,256G内存,个人存储1T)