当我们选择整个数据范围时,我们会在绘图区域内得到一个带有微小边距的绘图,这样绘图就不会触及边界框。但是,当我们对绘图进行子集化时,边距消失了。有没有办法添加这个边距?在下图中,我希望这条线一直到 5,但不要再进一步了。我浏览了?par
列表,但找不到可用的东西。
plot(1:10, 1:10, type = "l")
plot(1:10, 1:10, type = "l", xlim = c(1, 5))
这似乎是一种非常迂回的方式,但这是您提供的示例的一种可能性:
plot(1:10, 1:10, type = "n", xlim = c(1, 5))
usr = par("usr")
clip(usr[1], 5, usr[3], usr[4])
lines(1:10, 1:10, type = "l", xlim = c(1, 5))
您表达的担忧是不喜欢如何plot.default
处理传递给 xy.coords 的对象的限制。您希望它们受到限制或子集化。您可以通过定义具有这些附加功能的新绘图函数来做到这一点:
# need a helper function for this
tweak <- function(x) c(range(x)[1], range(x)[2]+.00001)
# Replace xy <- xy.coords(x, y, xlabel, ylabel, log)
xy <- xy.coords(x[findInterval(x, tweak(xlim))==1],
y[findInterval(x, tweak(xlim))==1],
xlabel, ylabel, log)
如果您的意图是保留 ylimit,则需要在调用或代码中指定它们。我的偏好是在通话中进行,但我将其说明为自动完成。
plotsub <- function(x,y = NULL, type = "p", xlim = NULL, ylim = NULL,
log = "", main = NULL, sub = NULL, xlab = NULL, ylab = NULL,
ann = par("ann"), axes = TRUE, frame.plot = axes, panel.first = NULL,
panel.last = NULL, asp = NA, ...)
{ ylim=range(y); tweak <- function(x) c(range(x)[1], range(x)[2]+.00001)
localAxis <- function(..., col, bg, pch, cex, lty, lwd) Axis(...)
localBox <- function(..., col, bg, pch, cex, lty, lwd) box(...)
localWindow <- function(..., col, bg, pch, cex, lty, lwd) plot.window(...)
localTitle <- function(..., col, bg, pch, cex, lty, lwd) title(...)
xlabel <- if (!missing(x))
deparse(substitute(x))
ylabel <- if (!missing(y))
deparse(substitute(y))
xy <- xy.coords(x[findInterval(x, tweak(xlim))==1], y[findInterval(x,tweak(xlim))==1], xlabel, ylabel, log)
xlab <- if (is.null(xlab))
xy$xlab
else xlab
ylab <- if (is.null(ylab))
xy$ylab
else ylab
xlim <- if (is.null(xlim))
range(xy$x[is.finite(xy$x)])
else xlim
ylim <- if (is.null(ylim))
range(xy$y[is.finite(xy$y)])
else ylim
dev.hold()
on.exit(dev.flush())
plot.new()
localWindow(xlim, ylim, log, asp, ...)
panel.first
plot.xy(xy, type, ...)
panel.last
if (axes) {
localAxis(if (is.null(y))
xy$x
else x, side = 1, ...)
localAxis(if (is.null(y))
x
else y, side = 2, ...)
}
if (frame.plot)
localBox(...)
if (ann)
localTitle(main = main, sub = sub, xlab = xlab, ylab = ylab,
...)
invisible()
}
来电:
plotsub(1:10, 1:10, type = "l", xlim = c(1, 5), ylim=c(1,10) )
您不是对数据进行子集化,而是对绘图设置限制。先验子集为您提供所需的行为。
plot(1:5, 1:5, type = "l")