njfrazie
njfrazie

Reputation: 91

R Programming: How to create a custom fit curve?

I'd like to create a graph that looks like this, but uses my own data for the min/max of the grey fit line enter image description here

Here is a simple plot.

df <- data.frame(x1 = c(0,1,2,3,4),
                 y1 = c(2,3,4,5,6),
                 x2 = c(0,1,2,3,4),
                 y2 = c(3,4,6,7,8),
                 x3 = c(0,1,2,3,4),
                 y3 = c(0,0,1,2.5,2))

g <- ggplot(data=df) +
  geom_line(aes(x1,y1,color="red")) + 
  geom_line(aes(x2,y2)) +
  geom_line(aes(x3,y3))

enter image description here

I want a transparent grey fill area like in the example to be behind the red line and between the 2 black lines. How do I accomplish this?

Upvotes: 0

Views: 282

Answers (1)

Michiel uit het Broek
Michiel uit het Broek

Reputation: 993

You can use the polygon function for this.

x <- 1:50
y_low <- rnorm(length(x), 150, 25) + 5*x
y_high <- rnorm(length(x), 250, 25) + 5*x

plot(x, y_high, type='l', ylim = c(000, 600))    
polygon(c(x, rev(x)), c(y_high, rev(y_low)), col = "grey40")

enter image description here

Another option (as mentioned in the comments) is to add the geom_ribbon attribute. You can specify customer values for the interval. The following did the work:

g <- ggplot(data=df) + geom_ribbon(aes(x=x1, ymin=y2, ymax=y3)) 
   + geom_line(aes(x1,y1,color="red")) 
   + geom_line(aes(x2,y2)) + geom_line(aes(x3,y3))

enter image description here

Upvotes: 2

Related Questions