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

时间:2014-08-08 04:57:49

标签: r plot

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

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")

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

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

如果您喜欢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)

enter image description here

编辑:

@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()
  }

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

df <- data.frame(x = runif(20,-10,10), y = runif(20,-10,10))
plot <- ggplot(df, aes(x,y))
colquad(plot)

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

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

答案 1 :(得分:3)

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

编写一个使用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])
}

请注意,在绘制点或它们之外,你必须这样做。在绘图函数中使用type='n'将使用一些数据设置空图:

> x = runif(20,-10,10) ; y = runif(20,-10,10)
> plot(x,y,type="n")
> quads()
> points(x,y)

通过colours= arg。

指定您自己的颜色