加载 R 包

library(ggplot2)
library(patchwork)
library(reshape2)

生成测试数据

# 生成一个 20x19 大小的矩阵,其中元素的值在 0-1 之间随机生成
testA = matrix(runif(n = 380, 0, 1), 20, 19)
# 给矩阵的列名添加前缀 'cancer' 和字母 A 到 S
colnames(testA) = paste0('cancer', LETTERS[1:19])
# 给矩阵的行名添加前缀 'sample' 和数字 1 到 20
row.names(testA) = paste0('sample', 1:20)
# 将矩阵转换为长格式的数据框,其中列名为 'cancer',行名为 'sample',值为 'exp'
dataA = melt(testA,
             varnames = c('sample', 'cancer'),
             value.name = 'exp')

自定义颜色函数

get_label_colors <- function(labels, pal = "Dark2", labels_unique = NULL, alpha = 1) {
  if (is.null(labels_unique)) {
    labels_unique <- sort(unique(labels))
  }
  palette <- RColorBrewer::brewer.pal(n = RColorBrewer::brewer.pal.info[pal, "maxcolors"], pal)
  
  lab2col <- list()
  i <- 1
  for (lab in labels_unique) {
    lab2col[[lab]] <- grDevices::adjustcolor(palette[(i - 1) %% length(palette) + 1], alpha)
    i <- i + 1
  }
  
  colors <- c()
  for (lab in labels) {
    colors <- c(colors, lab2col[[lab]])
  }
  
  colors
}

绘制小提琴图

# 生成颜色向量,颜色与标签一一对应
colors = get_label_colors(unique(dataA$cancer))

# 绘制小提琴图
p1 <- ggplot(dataA, aes(cancer, exp, fill = cancer)) + # 传递 x 轴和 y 轴,设置变量 fill
  geom_violin() +
  coord_flip() + # 变换 x 轴和 y 轴位置,小提琴图变为横向
  scale_fill_manual(values = colors) + # 设置颜色值,匹配自定义颜色变量 colors
  stat_summary(fun = mean, geom = "point", # 添加平均值点及其性状、大小、颜色
               shape = 19, size = 2, color = "black") +
  theme_bw() + # 设置黑白主题
  # 添加两条 0.6 和 0.3 的虚线
  geom_hline(aes(yintercept = 0.6), colour = "#565354", linetype = "dashed") +
  geom_hline(aes(yintercept = 0.3), colour = "#565354", linetype = "dashed") +
  xlab('') + # 设置 x 轴标签
  ylab('A indicator
indicator A') + # 设置 y 轴标签,\n 表示换行
  theme(panel.grid.major = element_blank(), # 消除主要网格线
        panel.grid.minor = element_blank(), # 消除次要网格线
        axis.text.y =  element_text(size = 12, # 设置 y 轴标签字体大小及加粗
                                    face = "bold"),
        legend.title = element_blank(), # 消除图例标题
        legend.position = 'none') # 不显示图例
p1

remove_y <- theme(
  axis.text.y = element_blank(),
  axis.ticks.y = element_blank(),
  axis.title.y = element_blank(),
)

# 生成四个图形对象
p <- list(
  p1,
  p1 + remove_y,
  p1 + remove_y,
  p1 + remove_y
)

# 将四个图形对象组合成一行
wrap_plots(p, nrow = 1)

# 将图形保存为 pdf 文件
ggsave('3.complex_violin.pdf', width = 8, height = 6)

代码优化建议

这段代码已经很简洁和优化了,没有明显的可以改进的地方。如果一定要说的话,可以考虑将一些重复的代码封装成函数,提高代码的可读性和复用性。比如,将绘制小提琴图的代码封装成一个函数,方便多次调用。

plot_violin <- function(data, colors) {
  ggplot(data, aes(cancer, exp, fill = cancer)) + # 传递 x 轴和 y 轴,设置变量 fill
    geom_violin() +
    coord_flip() + # 变换 x 轴和 y 轴位置,小提琴图变为横向
    scale_fill_manual(values = colors) + # 设置颜色值,匹配自定义颜色变量 colors
    stat_summary(fun = mean, geom = "point", # 添加平均值点及其性状、大小、颜色
                 shape = 19, size = 2, color = "black") +
    theme_bw() + # 设置黑白主题
    # 添加两条 0.6 和 0.3 的虚线
    geom_hline(aes(yintercept = 0.6), colour = "#565354", linetype = "dashed") +
    geom_hline(aes(yintercept = 0.3), colour = "#565354", linetype = "dashed") +
    xlab('') + # 设置 x 轴标签
    ylab('A indicator
indicator A') + # 设置 y 轴标签,\n 表示换行
    theme(panel.grid.major = element_blank(), # 消除主要网格线
          panel.grid.minor = element_blank(), # 消除次要网格线
          axis.text.y =  element_text(size = 12, # 设置 y 轴标签字体大小及加粗
                                      face = "bold"),
          legend.title = element_blank(), # 消除图例标题
          legend.position = 'none') # 不显示图例
}

# 生成颜色向量,颜色与标签一一对应
colors = get_label_colors(unique(dataA$cancer))

# 绘制小提琴图
p1 <- plot_violin(dataA, colors)

remove_y <- theme(
  axis.text.y = element_blank(),
  axis.ticks.y = element_blank(),
  axis.title.y = element_blank(),
)

# 生成四个图形对象
p <- list(
  p1,
  p1 + remove_y,
  p1 + remove_y,
  p1 + remove_y
)

# 将四个图形对象组合成一行
wrap_plots(p, nrow = 1)

# 将图形保存为 pdf 文件
ggsave('3.complex_violin.pdf', width = 8, height = 6)

这样,如果需要再次绘制小提琴图,只需调用 plot_violin() 函数即可,避免了重复代码,提高了代码的可读性和复用性。

R 包加载和使用示例:绘制小提琴图

原文地址: https://www.cveoy.top/t/topic/nJXh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录