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

如何用R的spatstat优化0/1标记点模式绘图并修正点大小

修正点模式绘图的点大小问题及优化方案

问题核心是plot.ppp默认会把数值型标记(哪怕是0/1)当作连续变量处理,自动映射为连续尺度的点大小。要实现两种固定大小,需手动指定大小映射,以下是具体修正方案:

方法一:将标记转为因子(更清晰的离散类别处理)

library(spatstat)

# 定义窗口多边形
x = c(3,0.5,1,0,0,0,2,2.5,5.5, 16,21,26,28,40, 47, 52, 58, 60, 65, 63, 63, 75, 77, 78, 75)
y = c(116,106,82.5,64,40,35,25,17.5,5,5,5,8,10,8, 14, 14, 10, 0, 0, 17, 20, 24, 30, 50, 116)
p <- owin(poly = cbind(x, y))

# 构建点模式并将标记转为因子
point_pattern = as.ppp(deviation_binary_locations_marks, p)
point_pattern$marks <- factor(point_pattern$marks$RPL32, levels = c(0,1), labels = c("0","1"))

# 定义颜色和固定大小映射
colour_map <- c("0" = "green", "1" = "black")
size_map <- c("0" = 1.5, "1" = 3)  # 可根据需求调整大小值

# 绘图
plot(point_pattern, 
     which.marks = "RPL32",
     pch = 21,  # 带填充色的圆形,区分度更高
     bg = colour_map[as.character(point_pattern$marks)],
     cex = size_map[as.character(point_pattern$marks)],
     main = "Point pattern for gene RPL32",
     legend = TRUE,
     legend.args = list(title = "RPL32 Mark", x = "bottomright"))  # 指定图例位置

方法二:直接基于数值标记映射(无需转因子)

如果不想转换标记类型,可利用0/1的数值索引直接映射颜色和大小:

library(spatstat)

x = c(3,0.5,1,0,0,0,2,2.5,5.5, 16,21,26,28,40, 47, 52, 58, 60, 65, 63, 63, 75, 77, 78, 75)
y = c(116,106,82.5,64,40,35,25,17.5,5,5,5,8,10,8, 14, 14, 10, 0, 0, 17, 20, 24, 30, 50, 116)
p <- owin(poly = cbind(x, y))

point_pattern = as.ppp(deviation_binary_locations_marks, p)
marks(point_pattern) <- deviation_binary_locations_marks[, "RPL32"]

# 0对应索引1,1对应索引2,直接映射颜色和大小
colour <- c("green", "black")[marks(point_pattern) + 1]
size <- c(1.5, 3)[marks(point_pattern) + 1]

# 绘图
plot(point_pattern, 
     which.marks = "RPL32",
     pch = 21,
     bg = colour,
     cex = size,
     main = "Point pattern for gene RPL32",
     legend = list(x = "bottomright", 
                   legend = c("0", "1"), 
                   fill = c("green", "black"),
                   pt.cex = c(1.5,3)))  # 图例点大小匹配绘图

优化细节说明

  • 点形状选择:pch=21是带填充色的圆形,可通过bg设置填充色,col设置边框色(如col="gray"统一边框),比默认形状更清晰。
  • 大小调整:size_map或size中的数值可按需修改,比如改成2和4提升视觉区分度。
  • 图例优化:通过legend.args或手动legend()函数指定位置,避免遮挡点模式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:20:35