r - 在 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]
解决方案
您会考虑使用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()
推荐阅读
- python - Colab 在我为时尚分类器预处理我的数据后给了我,尽管做了所有事情
- python - 你如何进行 blitted 整数更改?
- typescript - 从 TypeScript 中的 keyof 类派生的联合类型
- reactjs - 如何正确解决 React 更新状态(使用 useState / setState)但没有重新渲染组件的问题?
- amazon-dynamodb - AWS Amplify 解析其他用户的属性
- apache-spark - spark sql 有非聚集索引功能吗?
- django - Django - 在自定义模板后端获取请求实例
- c# - 功能间计时错误(C#、Unity)
- r - 将 ggplot2 中的图例更改为具有相似标签组
- logging - ESP_LOGx 消息中日志级别后的数字表示什么?