【问题标题】:plot points with by group in R data.table在 R data.table 中按组绘制点
【发布时间】:2026-02-23 08:30:01
【问题描述】:

我正在尝试使用 R data.table 中的 by 参数绘制点 - 计划是通过分组变量为点着色,但在开发中我注意到我认为很奇怪的行为。使用 data.table,jDT[i, j, by])中的操作应该在by 中的每个级别执行,例如

library(data.table)
dtcars <- copy(mtcars)
setDT(dtcars)
dtcars[, mean(mpg), by=cyl]

但我现在正试图让它分别为每个级别的 cyl 绘制点。黑点显示哪些数据应该以红色绘制,但当我使用 by 时,它似乎只适用于 cyl 为 8 的数据

dtcars[, plot(mpg~hp, typ="n")]
dtcars[, points(mpg~hp, col="black")]
dtcars[, points(mpg~hp, col="red"), by=cyl]

知道发生了什么,为什么它只作用于 cyl 的一个值,以及如何使用 by 为所有级别的 cyl 设置 R 绘图点?我使用了数据。表很多,以前没有注意到这种行为。


如果你能告诉我如何返回按值的索引,那么我就可以索引颜色,并给出与

相同的效果
dtcars[, points(mpg~hp, col=c("red", "blue", "green")[as.factor(cyl)])]

变成这样的人

dtcars[, points(mpg~hp, col=c("red", "blue", "green")[by_index]), by=cyl]

【问题讨论】:

  • 你为什么不用dtcars[, points(mpg~hp, col=cyl)]?对于组索引,检查?.GRP
  • 适用于这个例子,但计划是走得更远,达到我需要 bys 工作的地步 - 我主要只是好奇为什么 by 行为不起作用预计
  • 也感谢 .GRP 和搜索给我的其他特殊字符 @talat

标签: r data.table aggregate


【解决方案1】:

您会考虑使用ggplot2 代替base R 进行绘图吗?如果是这样,请尝试以下操作:

library(data.table)
library(ggplot2)

ggplot(mtcars, aes(x = hp, y = mpg, color = as.factor(cyl))) +
  geom_point() +
  scale_color_discrete(name = "cyl") +
  theme_linedraw()

【讨论】: