使用UpSetR绘制个性化UpSet图的技术问题求助
UpSetR绘图个性化修改方案(附ComplexUpset用法)
一、UpSetR 三大需求实现
1. 解决条形图上方数字重叠问题
直接调整text.scale参数缩小标签字号,针对性优化条形上方的计数标签,避免重叠:
# text.scale参数顺序:标题、横轴标签、纵轴标签、集合标签、条形上方数字、图例文字 upsetPlot <- upset( fromList(combined), text.scale = c(1.2, 1.2, 1, 1, 0.8, 1), order.by = "freq", keep.order = T, sets = rev(c("c0_prt", "c0_24h", "c4_12w", "c5_12w", "c7_12w")) )
2. 坐标轴刻度改为科学计数法
利用你定义的fancy_scientific()函数,通过mainbar.y.scale参数替换纵轴刻度:
# 保留你的科学计数法转换函数 fancy_scientific <- function(l) { l <- gsub("^0","0", l) l <- format(l, scientific = TRUE) l <- gsub("^(.*)e", "'\\1'e", l) l <- gsub("e", "%*%10^", l) parse(text=l) } # 绘图时指定纵轴刻度转换 upsetPlot <- upset( fromList(combined), mainbar.y.scale = fancy_scientific, text.scale = c(1.2, 1.2, 1, 1, 0.8, 1), order.by = "freq", keep.order = T, sets = rev(c("c0_prt", "c0_24h", "c4_12w", "c5_12w", "c7_12w")) )
3. 修改集合条形和交集点的颜色
给sets.bar.color传颜色向量设置每个集合的条形颜色,用point.color自定义交集点颜色:
# 自定义5个集合的条形颜色 set_colors <- c("#E69F00", "#56B4E9", "#009E73", "#F0E442", "#D55E00") upsetPlot <- upset( fromList(combined), sets.bar.color = set_colors, point.color = "#CC79A7", # 交集点统一颜色,也可传向量对应不同交集 mainbar.y.scale = fancy_scientific, text.scale = c(1.2, 1.2, 1, 1, 0.8, 1), order.by = "freq", keep.order = T, sets = rev(c("c0_prt", "c0_24h", "c4_12w", "c5_12w", "c7_12w")) ) upsetPlot
二、ComplexUpset 用法及集合标签加粗
ComplexUpset基于ggplot2,灵活性更强,实现步骤如下:
1. 数据格式转换
先将列表转成tidy格式的data.frame:
library(ComplexUpset) library(tidyr) library(ggplot2) # 转换为适合ComplexUpset的格式 combined_df <- enframe(combined, name = "set", value = "element") %>% unnest(value) %>% pivot_wider(names_from = set, values_from = set, values_fn = ~!is.na(.x), values_fill = FALSE)
2. 绘图并设置集合标签加粗
通过theme()中的axis.text.y设置集合标签为加粗字体,同时支持自定义颜色等样式:
upset( combined_df, intersect = colnames(combined_df)[-1], # 指定集合列 set_order = rev(c("c0_prt", "c0_24h", "c4_12w", "c5_12w", "c7_12w")), sort_intersections_by = 'cardinality', # 设置集合条形颜色 set_sizes = aes(fill = set), geom_set_size = geom_bar(show.legend = FALSE), fill = set_colors, # 设置交集点颜色 geom_point = geom_point(color = "#CC79A7", size = 3), # 集合标签加粗 theme = theme( axis.text.y = element_text(face = "bold", size = 11), # 可选:调整横轴标签字号避免重叠 axis.text.x = element_text(size = 9) ) )
内容的提问来源于stack exchange,提问作者Matteo
相关产品推荐
相关产品推荐

