R:仅更改特定区域的绘图背景颜色(基于 x 值) [英] R: change background color of plot for specific area only (based on x-values)

查看:73
本文介绍了R:仅更改特定区域的绘图背景颜色(基于 x 值)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I change the background color for a plot, only for a specific area? For example, from x=2 to x=4?

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

Bonus question: is it also possible for a combination of x and y coordinates? (for example from (1,2) to (3,4))?

非常感谢!

推荐答案

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

This can be achieved by thinking about the plot somewhat differently to your description. Basically, you want to draw a coloured rectangle between the desired positions on the x-axis, filling the entire y-axis limit range. This can be achieved using rect(), and note how, in the example below, I grab the user (usr) coordinates of the current plot to give me the limits on the y-axis and that we draw beyond these limits to ensure the full range is covered in the plot.

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 坐标向量开始,则更容易避免错误,如下所示:

rect() can draw a sequence of rectangles if we provide a vector of coordinates, and it can easily handle the case for the arbitrary x,y coordinates of your bonus, but for the latter it is easier to avoid mistakes if you start with a vector of X coordinates and another for the Y coordinates as below:

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

您可以像在奖金中一样轻松地获得数据:

You could just as easily have the data as you have it in the bonus:

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

这篇关于R:仅更改特定区域的绘图背景颜色(基于 x 值)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆