如何用ggplot绘制分类内呈S形排列的geom_point散点图
问题
我想要绘制每个分类下散点排列形成S形走势的可视化效果,请问是否可以在ggplot中实现该需求?
参考样图为每个分类下散点呈正弦S形排列的分组散点图,可获取同类公开示例数据用于测试。
我目前已完成的代码如下:
somatic.variants <- read.delim("data/Lawrence.S2.txt", stringsAsFactors=T) cancer_rates <- tapply(somatic.variants$logn_coding_mutations, somatic.variants$tumor_type, median) cancer_rates <- cancer_rates[order(cancer_rates, decreasing=F)] somatic.variants$tumor_type <- factor(somatic.variants$tumor_type, levels = names(cancer_rates)) library(ggplot2) library(GGally) ggplot(data = somatic.variants, mapping = aes(x = tumor_type, y = log10(n_coding_mutations))) + geom_point(position = position_dodge2()) + scale_x_discrete(position = "top") + scale_y_continuous(labels = c(0,10,100,1000,10000), expand = c(0,0)) + geom_stripped_cols() + theme_bw() + theme(axis.title.x = element_blank(), axis.text.x = element_text(angle = 315, hjust = 1, size = 12), panel.grid = element_blank()) + labs(y = "Coding mutations count") + stat_summary(fun = median, geom="crossbar", size = 0.25, width = 0.9, group = 1, show.legend = FALSE, color = "#FF0000")
实现方案
- 可以在ggplot中实现该效果,核心思路是对每个分组内的点按y值排序后,自定义x轴偏移量,使其按S形(正弦曲线走势)排列,具体修改步骤如下:
- 安装加载数据处理所需的dplyr包(已安装可跳过安装步骤):
install.packages("dplyr") library(dplyr)
- 对原始数据集做预处理,给每个分组内的点计算S形偏移量:
somatic.variants <- somatic.variants %>% group_by(tumor_type) %>% # 按y值排序后生成点序号 arrange(log10(n_coding_mutations)) %>% mutate( point_id = row_number(), # 计算正弦偏移,幅度0.4可调整控制摇摆宽度,3*pi可调整控制弯曲次数 x_offset = sin(seq(0, 3*pi, length.out = n())) * 0.4, # 分类变量转数值加上偏移得到实际x坐标 x_pos = as.numeric(tumor_type) + x_offset ) %>% ungroup()
- 修改ggplot绘图代码,替换x轴映射为计算好的偏移坐标,同时保留原分类标签显示:
ggplot(data = somatic.variants, mapping = aes(x = x_pos, y = log10(n_coding_mutations))) + geom_point(size = 0.8) + # 手动设置x轴刻度与原分类对应 scale_x_continuous( breaks = 1:length(levels(somatic.variants$tumor_type)), labels = levels(somatic.variants$tumor_type), position = "top", expand = c(0.05, 0.05) ) + scale_y_continuous(labels = c(0,10,100,1000,10000), expand = c(0,0)) + geom_stripped_cols() + theme_bw() + theme(axis.title.x = element_blank(), axis.text.x = element_text(angle = 315, hjust = 1, size = 12), panel.grid = element_blank()) + labs(y = "Coding mutations count") + stat_summary( # 中位数线映射回原分类位置,保证显示在每组中间 aes(x = as.numeric(tumor_type)), fun = median, geom="crossbar", size = 0.25, width = 0.9, group = 1, show.legend = FALSE, color = "#FF0000" )
- 参数调整说明:
- 增大
x_offset计算中sin()内的3*pi数值,可增加S形的弯曲次数 - 增大
x_offset计算中乘的系数0.4,可增大散点左右摇摆的宽度,反之则排列更窄
- 增大
内容的提问来源于stack exchange,提问作者Yuriy Grabovsky
相关产品推荐
相关产品推荐

