如何在Base R绘图中为不同菌株分配调色板并按cit分组着色
Base R散点图:多分组调色板匹配问题
需求与问题
需要绘制散点图:
- X轴:
elongation_time,Y轴:fluorescence - 数据按
strain(菌株)和cit两个维度分组 - 不同
strain使用专属调色板,每个cit在对应调色板中拥有唯一颜色 - 已将不同
strain数据拆分到NMmedians和cit20medians两个数据框,但设置col参数时出现问题:- 使用
as.factor(cit20medians$cit)无法切换到目标调色板 - 直接使用
darkcols无法与cit分组一一对应
- 使用
原尝试代码:
#defining my two palettes: darkcols <- c(cit0 = "#1548E0", cit3 = "#008F00", cit6 = "#CCAD00", cit9 = "#B85C00", citMax = "#B80000", citMin = "#8F008F") #for normalized cols <- c(cit0 = "royalblue2", cit3 = "green3", cit6 = "gold1", cit9 = "darkorange2", citMax = "red2", citMin = "magenta3") #for WT palette = cols pdf("20citvsNMwt.pdf", width = 2, height = 1.67, pointsize = 7, useDingbats = F, bg = "white" ) # sets margin stuff: par( mex = 0.65 ) par( mar = c(7,6.5,4,3) ) par( oma = c(0,0.5,1,0) ) #first plotting one strain (works as intended) plot( NMmedians$elongation_time, NMmedians$ratio, col = as.factor(NMmedians$cit), pch = 20, #cex = 0.6, axes = F, xlim = c(150,400), ylim = c(0,1), xlab = "", ylab = "fluorescence" ) #now trying to plot the other strain, the col parameter is where I've been focusing my efforts: points(cit20medians$elongation_time, cit20medians$ratio, pch = 20, col = list(darkcols, as.factor(cit20medians$cit)) ) axis( 1 ) axis( 2 ) title( xlab = "elongation time", line = 4.5 ) dev.off()
解决方案
核心思路:利用命名调色板向量的特性,通过cit列的取值直接索引对应调色板中的颜色,确保每个cit分组匹配到正确的颜色。
修正后的代码:
# 定义两个命名调色板 darkcols <- c(cit0 = "#1548E0", cit3 = "#008F00", cit6 = "#CCAD00", cit9 = "#B85C00", citMax = "#B80000", citMin = "#8F008F") # 对应normalized菌株 cols <- c(cit0 = "royalblue2", cit3 = "green3", cit6 = "gold1", cit9 = "darkorange2", citMax = "red2", citMin = "magenta3") # 对应WT菌株 pdf("20citvsNMwt.pdf", width = 2, height = 1.67, pointsize = 7, useDingbats = F, bg = "white" ) # 设置绘图边距 par( mex = 0.65 ) par( mar = c(7,6.5,4,3) ) par( oma = c(0,0.5,1,0) ) # 绘制第一个菌株:通过cit值索引cols调色板 plot( NMmedians$elongation_time, NMmedians$ratio, col = cols[as.character(NMmedians$cit)], # 关键:用cit字符串匹配调色板的命名 pch = 20, axes = F, xlim = c(150,400), ylim = c(0,1), xlab = "", ylab = "fluorescence" ) # 绘制第二个菌株:通过cit值索引darkcols调色板 points(cit20medians$elongation_time, cit20medians$ratio, pch = 20, col = darkcols[as.character(cit20medians$cit)] # 同样用cit字符串匹配命名调色板 ) axis( 1 ) axis( 2 ) title( xlab = "elongation time", line = 4.5 ) dev.off()
关键说明
- 原代码问题:
as.factor(NMmedians$cit)会把cit转换为整数水平,默认调用当前全局palette的对应位置颜色,无法自动切换到指定调色板- 直接使用
darkcols会将整个颜色向量重复填充,无法与每个数据点的cit分组一一对应
- 修正逻辑:
- 调色板是命名向量,每个颜色的名字与
cit的取值完全对应 - 将
cit列转换为字符型(as.character()),作为索引从调色板中取出对应颜色,确保每个数据点匹配到正确的分组颜色
- 调色板是命名向量,每个颜色的名字与
内容的提问来源于stack exchange,提问作者Loud
相关产品推荐
相关产品推荐

