【问题标题】:Getting different results using ggplot and base plot functions使用 ggplot 和基本绘图函数获得不同的结果
【发布时间】:2014-10-23 08:01:26
【问题描述】:

我在这里有一张桌子:http://ulozto.cz/xAeP3Ahn/res2-txt。我正在尝试从中绘制点图。

我读了我的表:

res2<-read.table("res2.txt", header = TRUE, sep="\t")

并创建 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))

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

这是我的结果:

我的问题是,为什么我在生成的绘图中有不同的点位置?问题只是颜色和图例不同吗?那么“子集”定义错了吗?为什么 2006 年在两者中都标记为红色,但在图中的位置不同? 2011年和其他人一样吗?我哪里错了?感谢您的每一个建议,我在第三天迷路了。

这是我从 excel 得到的结果,所以 ggplot2 (2) 的情节必须是正确的

【问题讨论】:

  • 我不认为情节 (1) 是由您问题中的代码生成的。试试:subset(res2$V2, year == 2006)numeric(0).
  • 不是您问题的答案,但为了避免多次point 调用,每年一次,您可以通过将“col”向量与“year”列子集来创建颜色向量:@ 987654330@; points(dist06 ~ V2, data = res2, col = col[factor(res2$year)])

标签: r charts plot subset


【解决方案1】:

我想这是subset 使用不正确的副作用。它的第一个参数应该是整个数据框,如下所示:

subset(res2, year == 2006)$V2

subset(res2, year == 2006, select = V2)

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

我建议使用括号表示法:

res2$V2[res2$year == 2006]

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

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

【讨论】:

  • 感谢@tonytonov,我永远不会想到这一点!我已经按照您的建议更改了“子集”,并且可以正常工作,再次感谢! :)
猜你喜欢
  • 2021-08-24
  • 1970-01-01
  • 2012-08-08
  • 2021-07-16
  • 2019-04-14
  • 2022-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多