Data.table没有返回正确的图

时间:2017-04-21 07:32:28

标签: r plot data.table

开始学习data.table包并想尝试绘图。

library(data.table)
DT <- data.table(iris)

DT[, plot(Sepal.Length, Sepal.Width, main = Species), by = Species]

不会返回与例如

相同的内容
DT1 <- DT[Species == "setosa"]
DT1[, plot(Sepal.Length, Sepal.Width, main = Species)]

第二个显示所有观察结果,而第一个观察结果则没有。

我还没有学到完美的逻辑解释吗?或者我的图形有问题?

2 个答案:

答案 0 :(得分:3)

Saving plots in a data.table list column报告了问题和解决方法。

由于plot()正在按预期工作,因此问题似乎与基础ggplot2有关,例如,

library(data.table)
DT[, print(ggplot(.SD, aes(Sepal.Length, Sepal.Width, color = Species)) +
             geom_point()), by = Species]
例如,

创建一系列三个图,这些图显示在RStudio的“图”窗格中。第一个看起来像:

enter image description here

但是,基数plot()

par(mfrow=c(1,3))
DT[, plot(Sepal.Length, Sepal.Width, main = Species), by = Species]

某些数据点已被剪掉:

enter image description here

Frank in his comment 所述,一种解决方法是确保变量按值传递,例如,添加0。因此,此解决方法将创建包含所有数据点的基础图:

par(mfrow=c(1,3))
DT[, plot(Sepal.Length + 0, Sepal.Width + 0, main = Species), by = Species]

enter image description here

请注意,0必须添加到两个变量中。

编辑如果使用非数字数据(因此添加0并不可行), Frank suggested使用其他方法按值传递数据

DT[, with(copy(.SD), plot(Sepal.Length, Sepal.Width, main = Species)), by = Species]

答案 1 :(得分:0)

在第一部分中,您尝试绘制每个物种等级的两个变量。尝试改变标准杆,看看你想要达到的目标:

par(mfrow=c(1,3))
DT[, plot(Sepal.Length, Sepal.Width, main = Species), by = Species]

在第二个实例中,您绘制了虹膜,但没有指定条件变量,重复主列(我想!)