用不同颜色为散点图中每个象限的背景着色

use*_*545 3 plot r

假设我生成了这个散点图:

plot(x = runif(20,-10,10), y = runif(20,-10,10), xlim = c(-10,10), ylim = c(-10,10))
abline(h = 0, col = "black")
abline(v = 0, col = "black")
Run Code Online (Sandbox Code Playgroud)

所以abline's 将平面划分为四个笛卡尔象限。我想用不同的颜色为每个象限的背景着色。分别为 1-4 象限说蓝色、红色、绿色和黄色。

任何的想法?

BBr*_*ill 7

如果您喜欢 ggplot 解决方案:

df <- data.frame(x = runif(20,-10,10), y = runif(20,-10,10))
    ggplot(df, aes(x,y)) + 
      annotate("rect", xmin = Inf, xmax = 0, ymin = Inf, ymax = 0, fill= "red")  + 
      annotate("rect", xmin = -Inf, xmax = 0, ymin = -Inf, ymax = 0 , fill= "blue") + 
      annotate("rect", xmin = 0, xmax = Inf, ymin = 0, ymax = -Inf, fill= "yellow") + 
      annotate("rect", xmin = 0, xmax = -Inf, ymin = Inf, ymax = 0, fill= "green") + 
      geom_point() + xlim(-10,10)+ ylim(-10,10)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

编辑:

@Spacedman:我不知道有些设备会遇到 Inf 的问题,这里不使用 Inf 的函数,还允许选择象限的交叉点和颜色

colquad <- function(plot, crossAt = 0, xlims = c(-10,10), ylims = c(-10,10), colours = c("blue", "red","yellow", "green")) {
  #colours of rects are from left to right starting at the top
    library(ggplot2)
    plot <- plot + coord_cartesian(xlim = c(xlims[1],xlims[2]), ylim = c(ylims[1], ylims[2])) 
    plot + 
      annotate("rect", xmin = xlims[1], xmax = crossAt, ymin = ylims[2], ymax = crossAt, fill = colours[1]) + 
      annotate("rect", xmin = crossAt, xmax = xlims[2], ymin = crossAt, ymax = ylims[2], fill = colours[2])  +
      annotate("rect", xmin = xlims[1], xmax = crossAt, ymin = ylims[1], ymax = crossAt , fill= colours[3]) + 
      annotate("rect", xmin = crossAt, xmax = xlims[2], ymin = crossAt, ymax = ylims[1], fill = colours[4]) + 
      geom_point()
  }
Run Code Online (Sandbox Code Playgroud)

使用它(制作之前的图表):

df <- data.frame(x = runif(20,-10,10), y = runif(20,-10,10))
plot <- ggplot(df, aes(x,y))
colquad(plot)
Run Code Online (Sandbox Code Playgroud)

以及ggplot2优势的一个例子,将点的颜色更改为白色

colquad(plot) %+% geom_point(colour = "white")


Spa*_*man 5

您正在使用基本图形,所以这里有一个基本图形解决方案。

编写一个函数,使用rect并从par()$usr以下位置获取绘图限制:

quads =
function(colours=c("blue","red","green","yellow")){
  limits = par()$usr
  rect(0,0,limits[2],limits[4],col=colours[1])
  rect(0,0,limits[1],limits[4],col=colours[2])
  rect(0,0,limits[1],limits[3],col=colours[3])
  rect(0,0,limits[2],limits[3],col=colours[4])
}
Run Code Online (Sandbox Code Playgroud)

请注意,您必须在绘制点之前执行此操作,否则它会覆盖它们。使用type='n'在绘图功能将设置一些数据的空情节:

> x = runif(20,-10,10) ; y = runif(20,-10,10)
> plot(x,y,type="n")
> quads()
> points(x,y)
Run Code Online (Sandbox Code Playgroud)

通过colours=arg指定您自己的颜色。