使用ggplot和基本绘图函数获得不同的结果

may*_*cca 5 charts plot r subset

我在这里有一张桌子:http://ulozto.cz/xAeP3Ahn/res2-txt.我试图从中得出一个点图.

我读了我的桌子:

res2<-read.table("res2.txt", header = TRUE, sep="\t")
Run Code Online (Sandbox Code Playgroud)

并创建2个图.

(1)这是单个绘图功能的脚本:

plot(res2$V2, res2$dist06, type = "n")
points(subset(res2$V2, year == 2006), subset(res2$dist06, year == 2006), pch = 19, col   = "red", cex = 1)
points(subset(res2$V2, year == 2007), subset(res2$dist06, year == 2007), pch = 19, col = "green", cex = 1)
points(subset(res2$V2, year == 2008), subset(res2$dist06, year == 2008), pch = 19, col = "black", cex = 1)
points(subset(res2$V2, year == 2009), subset(res2$dist06, year == 2009), pch = 19, col = "blue", cex = 1)
points(subset(res2$V2, year == 2011), subset(res2$dist06, year == 2011), pch = 19, col = "yellow", cex = 1)
legend("topright", c("2006", "2007", "2008", "2009", "2011"),
   col= c("red", "green", "black", "blue", "yellow"),
   pch = c(19,19,19,19,19))
Run Code Online (Sandbox Code Playgroud)

(2)和ggplot2:

res2$year<-as.factor(res2$year)  # consider year variable as discrete
ggplot(data=res2, aes(x=V2, y=dist06, color=year)) + geom_point(shape=16, pch=50) +
    xlab("threshold") + ylab("Euclidean distance") + 
    scale_fill_hue(name="year") + # set legend title 
    scale_colour_manual(values=c("red", "green", "black", "blue", "yellow")) +
    theme_bw() 
Run Code Online (Sandbox Code Playgroud)

这是我的结果:

简单绘图函数(1)和froom ggplot2(2)的结果

我的问题是,为什么我在不同的情节中有不同的分数位置?问题只是在不同的颜色和传奇?那么"子集"定义错了吗?为什么2006年两者都被标记为红色,但在图表中有不同的位置?和2011年和其他人一样吗?我哪里错了?谢谢你的每一个建议,我在这里失去了第三天.

这是我从excel得到的结果,所以ggplot2(2)的情节必须是正确的 从excel中的相同数据绘制图表

ton*_*nov 4

我认为这是错误使用的副作用subset。它的第一个参数应该是整个数据框,如下所示:

subset(res2, year == 2006)$V2
Run Code Online (Sandbox Code Playgroud)

或者

subset(res2, year == 2006, select = V2)
Run Code Online (Sandbox Code Playgroud)

(旁注:这些命令返回的对象不同,但两者都适用于您的绘图)

我建议使用括号表示法:

res2$V2[res2$year == 2006]
Run Code Online (Sandbox Code Playgroud)

无论哪种方式,你都会得到正确的情节:

在此输入图像描述

正如您可能已经注意到的,您不必使用ggplot方法进行大量复制/粘贴。好的!