Search code examples
rggplot2background-coloroverlapscatter

How to add different background colors between lines in a scatter plot using R?


I want to use R to draw a scatter plot like this:

enter image description here

It is a scatter plot. And there are three lines on it. Under the first line (x=(3,0), y=(0,2)), I want the background color to be light red. And red is between the first and the second line (x=(4,0),y=(0,4)). Then dark red is between the second and the third line (x=(8,0),y=(0,5)).

Let's say the scatter data is:

a=data.frame(x=c(1,2,3,4,5,6,7,8,9,10),
             y=c(1,4,2,6,4,8,2,5,1,7))

How can I achieve this?


Solution

  • Use geom_point for the scatter data and geom_polygon to draw and fill the areas.

    geom_polygon conects the x-y points, start and end points are connected and the inside is coloured by fill (more details here)

    In the following example, all polygons start at 0,0

    pol.3 = data.frame(x=c(0,8,0), y=c(0,0,5))
    pol.2 = data.frame(x=c(0,4,0), y=c(0,0,4))
    pol.1 = data.frame(x=c(0,3,0), y=c(0,0,2))
    
    ggplot(a) + 
      geom_polygon(data=pol.3, aes(x=x, y=y), fill = "blue") +
      geom_polygon(data=pol.2, aes(x=x, y=y), fill = "green") +
      geom_polygon(data=pol.1, aes(x=x, y=y), fill = "red") + 
      geom_point(aes(x=x, y=y)) 
    

    enter image description here

    If you do not want your polygons to overlap, use the following data

    pol.3 = data.frame(x=c(4,8,0,0), y=c(0,0,5,4))
    pol.2 = data.frame(x=c(3,4,0, 0), y=c(0,0,4,2))
    pol.1 = data.frame(x=c(0,3,0), y=c(0,0,2))
    

    The result will be the same but with no overlap so you can use alpha to tune the filling colors