使用R网格包的行

时间:2012-09-11 19:28:40

标签: r graphics

我正在使用R和cygwin,我试图绘制一些基本的图形。以下是Paul Murrell的一篇论文中的一个简单例子:

library(grid)
x <- rnorm(50)
y <- x + rnorm(50, 1, 2)
rx <- range(x)
dx <- diff(rx)
ry <- range(y)
dy <- diff(ry)
max <- max(rx, ry)
min <- min(rx, ry)
r <- c(min(rx, ry), max(rx, ry))
d <- diff(r)
scale <- r + c(-1, 1) * d * 0.05
extscale <- c(min(scale), max(scale) + diff(scale) * 1/3)
lay <- grid.layout(2, 2, 
                   widths = unit(c(3, 1), "inches"), 
                   heights = unit(c(1, 3), "inches"))
vp1 <- viewport(w = unit(4, "inches"), h = unit(4, "inches"), 
                layout = lay, xscale = extscale, yscale = extscale)
grid.newpage()
pushViewport(vp1)
grid.rect()
grid.xaxis()
grid.text("Test", y = unit(-3, "lines"))
grid.yaxis()
grid.text("Retest", x = unit(-3, "lines"), rot = 90)
vp2 <- viewport(layout.pos.row = 2, layout.pos.col = 1, 
                xscale = scale, yscale = scale)
pushViewport(vp2)
grid.lines()
grid.points(x, y, gp = gpar(col = "blue"))

这很好。但是,如果我在程序中添加以下行:

grid.lines(x, y, gp = gpar(col = "red"))

线条到处都是。我曾预料到线路会按顺序连接点。我在编写的代码中遇到了类似的问题,但是线条的图表很好,但点数没有。

非常感谢任何帮助。感谢。

1 个答案:

答案 0 :(得分:3)

出于某种原因,grid.points()grid.lines()具有不同的“默认单位”。 (这些是单位 - "native""npc" - 当您将函数传递给没有任何关联单位的数字向量时使用。)

args(grid.lines)
# function (x = unit(c(0, 1), "npc"), y = unit(c(0, 1), "npc"), 
#     default.units = "npc", arrow = NULL, name = NULL, gp = gpar(), 
#     draw = TRUE, vp = NULL)     
args(grid.points)
# function (x = stats::runif(10), y = stats::runif(10), pch = 1, 
#     size = unit(1, "char"), default.units = "native", name = NULL, 
#     gp = gpar(), draw = TRUE, vp = NULL) 

快速解决方案是明确设置grid.lines()的默认单位以匹配grid.points()使用的单位:

grid.lines(x, y, gp = gpar(col = "red"), default.units = "native")

enter image description here