问题 R:仅更改特定区域的绘图背景颜色(基于x值)


如何更改绘图的背景颜色,仅针对特定区域? 例如,从x = 2到x = 4?

额外问题:x和y坐标的组合是否也可能? (例如从(1,2)到(3,4))?

非常感谢!


9642
2018-01-05 10:34


起源



答案:


这可以通过考虑与您的描述略有不同的情节来实现。基本上,您希望在x轴上的所需位置之间绘制一个彩色矩形,填充整个y轴限制范围。这可以通过使用来实现 rect(),并注意在下面的示例中,我如何抓住用户(usr)当前图的坐标给出了我对y轴的限制,并且我们超出这些限制以确保图中涵盖了整个范围。

plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(2, lim[3]-1, 4, lim[4]+1, border = "red", col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

rect() 如果我们提供一个坐标向量,它可以绘制一系列矩形,它可以很容易地处理你的奖金的任意x,y坐标的情况,但对于后者,如果你从X的向量开始,更容易避免错误坐标和另一个Y坐标如下:

X <- c(1,3)
Y <- c(2,4)
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(X[1], Y[1], X[2], Y[2], border = "red", col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

您可以轻松获得奖金中的数据:

botleft <- c(1,2)
topright <- c(3,4)
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(botleft[1], botleft[2], topright[1], topright[2], border = "red",
     col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

16
2018-01-05 11:01



你也可以使用 polygon 遮蔽更复杂的地区。 - Carl Witthoft
对于一些 plot 方法至少,你也可以包装 rect 打电话给 panel.first - baptiste
两点都好! - Gavin Simpson
谢谢! rect()命令比polygon更直观,而par('usr')技巧是救生员!对于那些对使用透明色彩感兴趣的人,我发现rgb(1,1,1,0.5)对于透明灰色作品来说很棒。 - struggleBus


答案:


这可以通过考虑与您的描述略有不同的情节来实现。基本上,您希望在x轴上的所需位置之间绘制一个彩色矩形,填充整个y轴限制范围。这可以通过使用来实现 rect(),并注意在下面的示例中,我如何抓住用户(usr)当前图的坐标给出了我对y轴的限制,并且我们超出这些限制以确保图中涵盖了整个范围。

plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(2, lim[3]-1, 4, lim[4]+1, border = "red", col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

rect() 如果我们提供一个坐标向量,它可以绘制一系列矩形,它可以很容易地处理你的奖金的任意x,y坐标的情况,但对于后者,如果你从X的向量开始,更容易避免错误坐标和另一个Y坐标如下:

X <- c(1,3)
Y <- c(2,4)
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(X[1], Y[1], X[2], Y[2], border = "red", col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

您可以轻松获得奖金中的数据:

botleft <- c(1,2)
topright <- c(3,4)
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(botleft[1], botleft[2], topright[1], topright[2], border = "red",
     col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

16
2018-01-05 11:01



你也可以使用 polygon 遮蔽更复杂的地区。 - Carl Witthoft
对于一些 plot 方法至少,你也可以包装 rect 打电话给 panel.first - baptiste
两点都好! - Gavin Simpson
谢谢! rect()命令比polygon更直观,而par('usr')技巧是救生员!对于那些对使用透明色彩感兴趣的人,我发现rgb(1,1,1,0.5)对于透明灰色作品来说很棒。 - struggleBus