首页 > 解决方案 > 在 R data.table 中按组绘制点

问题描述

我正在尝试使用 R data.table 中的 by 参数绘制点 - 计划是通过分组变量为点着色,但在开发中我注意到我认为奇怪的行为。使用 data.table,j(of DT[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 的一个值以及如何为所有级别的 cyl 设置 R 绘图点,用 by?我经常使用 data.table 并且以前没有注意到这种行为。


如果您能告诉我如何返回按值的索引,则可以加分,这样我就可以索引颜色,从而产生与

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]

标签: rdata.tableaggregate

解决方案


您会考虑使用ggplot2而不是基础 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()

推荐阅读