简体   繁体   English

在 R data.table 中按组绘制点

[英]plot points with by group in R data.table

I am trying to plot points using a by argument in R data.table - the plan is to colour the points by the grouping variable, but in development I noticed a behaviour I thought was strange.我正在尝试使用 R data.table 中的 by 参数绘制点 - 计划是通过分组变量为点着色,但在开发中我注意到一种我认为很奇怪的行为。 With data.table, the operation in j (of DT[i, j, by] ) is supposed to be carried out per level in the by , eg使用 data.table, j ( DT[i, j, by] ) 中的操作应该在by每个级别执行,例如

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

But I am now trying to get this to plot points for each level of cyl separately.但我现在试图让它分别为每个级别的 cyl 绘制点。 The black points are showing what data should be getting plotted in red, but it only seems to do those where cyl is 8 when I use the by黑点显示应该以红色绘制哪些数据,但当我使用 by 时,它似乎只显示 cyl 为 8

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

Any idea what is going on, why it is only acting on the one value of cyl and how to have R plot points for all levels of cyl, with by?知道发生了什么,为什么它只作用于 cyl 的一个值以及如何为所有级别的 cyl 设置 R 绘图点,by? I've used data.table a lot and not noticed this behaviour before.我经常使用 data.table 并且以前没有注意到这种行为。


Bonus points if you can tell me how to return the index of the by value so I can index the colours giving the same effect as如果您能告诉我如何返回 by 值的索引,那么我就可以为颜色编制索引,从而获得与以下相同的效果

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

Becoming something like变得像

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

Would you consider using ggplot2 instead of base R for plotting?您会考虑使用ggplot2而不是基数 R 进行绘图吗? If so, try the following :如果是这样,请尝试以下操作:

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM