You need to enable JavaScript to run this app. 使用R基础绘图绘制dotplot:轴交换、按species着色及同组连线咨询
优惠活动
大模型
产品
解决方案
定价
更多

使用R基础绘图绘制dotplot:轴交换、按species着色及同组连线咨询

R基础绘图实现指定样式点图

你当前使用的dotplot()属于lattice包函数,以下方案完全基于R基础绘图函数实现,不依赖ggplot2、lattice等扩展包,满足所有需求:

第一步:构建数据集

先运行以下代码导入你的数据集:

df <- structure(list(species = c("asinus", "asinus", "asinus", "asinus", "asinus", "caballus", "caballus", "caballus", "caballus", "caballus", "grevy", "grevy", "grevy", "grevy", "grevy", "kiang", "kiang", "kiang", "kiang", "kiang"), measurement = c(1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L, 1L, 2L, 3L, 4L, 5L), test = c(73.6, 67.1, 24.5, 39.8, 29, 79.8, 71.7, 33.4, 52.9, 34.7, 85.5, 78.9, 30.2, 50.2, 35, 85, 79.4, 25.9, 43.7, 32.1), ref = c(76.6, 69.9, 24.8, 41.1, 31, 76.6, 69.9, 24.8, 41.1, 31, 76.6, 69.9, 24.8, 41.1, 31, 76.6, 69.9, 24.8, 41.1, 31), log = c(-0.0399520510117144, -0.0408816052621281, -0.0121705356202551, -0.0321412092117974, -0.0666913744986721, 0.0409264277092181, 0.0254250983658109, 0.297712246811718, 0.252395217362064, 0.112752482467667, 0.10991929919617, 0.121115578612065, 0.196998271209887, 0.200006905195494, 0.121360857004267, 0.104054179743772, 0.127432719013326, 0.0433993155345553, 0.0613399805993553, 0.0348688256508241)), class = "data.frame", row.names = c(NA, -20L))

第二步:运行绘图代码

# 预定义物种对应的配色,可根据需求自行修改颜色值
sp_col <- setNames(c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3"), unique(df$species))

# 初始化空白画布,设置坐标轴对应关系,x为measurement,y为log值
plot(
  x = df$measurement, 
  y = df$log, 
  type = "n", # 先不绘制任何元素
  xlab = "Measurement", 
  ylab = "Log value",
  main = "Species Measurement Dot Plot",
  xaxt = "n" # 暂时隐藏x轴,后续自定义刻度
)
# 自定义x轴刻度,对应1-5的measurement取值
axis(side = 1, at = 1:5, labels = 1:5)

# 按物种分组绘制连线和点
for (sp in unique(df$species)) {
  sp_sub <- df[df$species == sp, ]
  # 先绘制同物种的连线
  lines(x = sp_sub$measurement, y = sp_sub$log, col = sp_col[sp], lwd = 1.5)
  # 再绘制对应颜色的点,避免点被连线遮挡
  points(x = sp_sub$measurement, y = sp_sub$log, col = sp_col[sp], pch = 16, cex = 1.2)
}

# 添加物种图例
legend("topleft", legend = names(sp_col), col = sp_col, pch = 16, lwd = 1.5, title = "Species")

需求匹配说明

  • 坐标轴交换:初始化plot时直接指定x轴为measurement列、y轴为log列,满足坐标轴交换需求
  • 物种颜色编码:提前为每个物种分配唯一配色,绘制连线和点时均使用对应物种的颜色,区分度高
  • 同物种连线:按物种分组遍历,先调用lines()连接同一物种的所有点,再绘制点,视觉层级合理

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 22:24:03