You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2折线图中让标记的红色线条置于顶层?

问题描述

使用ggplot2绘制基因表达折线图时,希望将标记基因的红色线条置于其他黑色线条上方以提升可读性,但调整geom_line写法后始终无法实现。

原代码如下:

#Plot linegraph of gene lists of interest (e.g. most common cluster genes) per cell type
for (j in 1:length(clusters)) {
  #Lookup gene list
  ind=match(rownames(gene_list)[gene_list$Cluster==clusters[j]], rownames(eset))
  #Build matrix of avg common gene exp over time per cell type
  gene_list_line_FC_mat=vector("list",length(cell_types_plot))
  for (k in 1:length(cell_types_plot)) {
    gene_list_line_FC_mat[[k]]=array(NA, dim=c(length(ind),ncol(eset_mean_D0FC[[cell_types_plot[k]]])+1),
                                     dimnames=list(rownames(eset)[ind],c(0,tp)))
    #Set D0 FC to 0
    gene_list_line_FC_mat[[k]][,1]=0
    gene_list_line_FC_mat[[k]][,-1]=exprs(eset_mean_D0FC[[cell_types_plot[k]]][ind,])
    #Convert matrix to long format
    gene_list_line_FC_mat[[k]]=data.frame(gene_list_line_FC_mat[[k]]) %>% tibble::rownames_to_column(var = "Gene") %>%
      pivot_longer(-Gene, names_to='Timepoint', values_to='FC')
    #Convert timepoint back to numeric
    gene_list_line_FC_mat[[k]]$Timepoint=as.numeric(str_replace(gene_list_line_FC_mat[[k]]$Timepoint, 'X', ''))
    #Add cell type column
    gene_list_line_FC_mat[[k]]$Cell_type=cell_types_plot[k]
  }
  #Combine results from each cell type
  gene_list_line_FC_mat=do.call(rbind, gene_list_line_FC_mat)
  #Find top n genes based on FC for labeling (at tp_max in cell_type_max)
  genes_label=gene_list_line_FC_mat$Gene[
    gene_list_line_FC_mat$Timepoint==tp_max_label & gene_list_line_FC_mat$Cell_type==cell_type_max_label][
      order(-gene_list_line_FC_mat$FC[gene_list_line_FC_mat$Timepoint==tp_max_label & gene_list_line_FC_mat$Cell_type==cell_type_max_label])[1:n_genes_label]]
  genes_label=gene_list_line_FC_mat$Label=genes_label=gene_list_line_FC_mat$Gene %in% genes_label
  #Change cell type to factor for plotting order
  gene_list_line_FC_mat$Cell_type=factor(gene_list_line_FC_mat$Cell_type, levels=cell_types_plot)
  #Plot
  ggplot(gene_list_line_FC_mat, aes(x=Timepoint, y=FC, group=Gene)) +
    geom_line(linewidth=1, aes(color=Label), show.legend=F)+
    scale_colour_manual(values=c('TRUE'='red','FALSE'='black'))+
    geom_label_repel(data=gene_list_line_FC_mat[gene_list_line_FC_mat$Timepoint==8 & gene_list_line_FC_mat$Label==T,], aes(label=Gene),
                     nudge_x=1, max.overlaps=10)+
    theme_classic()+
    scale_x_continuous(breaks=c(0,tp))+
    xlab("Day post-infection")+
    ylab("Mean FC (log2)")+
    ggtitle(paste("Cluster",j))+
    theme(plot.title = element_text(hjust = 0.5), text = element_text(size=20))+
    facet_wrap(~Cell_type)
  ggsave(file.path(module_filename,paste0(module_filename,"_gene_linegraph_TFS_MDM_cluster",j,".pdf")), width = 15, height = 10)
}

折线图示例:
基因表达折线图

解决方案

ggplot2的图层按代码顺序绘制,后添加的图层会覆盖在之前的图层之上。因此无需用单个geom_line区分颜色,分两步绘制即可实现需求:

  • 先绘制所有非标记基因的黑色线条
  • 再绘制标记基因的红色线条

修改后的绘图代码部分如下(替换原代码中#Plot后的ggplot代码块):

#Plot
ggplot(gene_list_line_FC_mat, aes(x=Timepoint, y=FC, group=Gene)) +
  # 先画非标记基因的黑色线条
  geom_line(data = subset(gene_list_line_FC_mat, Label == FALSE), 
            linewidth=1, color='black', show.legend=F)+
  # 再画标记基因的红色线条,置于上层
  geom_line(data = subset(gene_list_line_FC_mat, Label == TRUE), 
            linewidth=1, color='red', show.legend=F)+
  geom_label_repel(data=gene_list_line_FC_mat[gene_list_line_FC_mat$Timepoint==8 & gene_list_line_FC_mat$Label==T,], 
                   aes(label=Gene), nudge_x=1, max.overlaps=10)+
  theme_classic()+
  scale_x_continuous(breaks=c(0,tp))+
  xlab("感染后天数")+
  ylab("平均倍数变化(log2)")+
  ggtitle(paste("Cluster",j))+
  theme(plot.title = element_text(hjust = 0.5), text = element_text(size=20))+
  facet_wrap(~Cell_type)
ggsave(file.path(module_filename,paste0(module_filename,"_gene_linegraph_TFS_MDM_cluster",j,".pdf")), width = 15, height = 10)

说明

  • 通过subset()分别筛选非标记和标记基因的数据,分两次调用geom_line
  • 先画黑色线条,再画红色线条,确保红色线条覆盖在黑色线条上方
  • 移除原代码中的scale_colour_manual,颜色直接在geom_line中指定

内容的提问来源于stack exchange,提问作者Hammonje

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 00:15:07