Reputation: 19
I am new to R and tried to hatch draw an area which is bounded by some linear functions. For my functions i wrote following code:
library(ggplot2)
library(dplyr)
x <- seq(0,30,1)
y1 <- (60-2*x)/0.8
y2 <- (90-4*x)/0.4
y3 <- (150-6*x)/0.8
df <- tbl_df(data.frame(x,y1,y2,y3))
df %>%
ggplot(aes(x=x,y=y1))+
geom_line(y=y1,color="red")+
geom_line(y=y2,color="blue")+
geom_line(y=y3,color="green")+
ylim(0,225)
which plots me perfectly what i want. I just want to have the orange area like i drew in the picture: sketch
The coordinates where the functions intersect are x=(0,15,22.5,30) and y(225,75,18.75,0) if that helps.
Upvotes: 0
Views: 689
Reputation: 5214
Building off of the answer from kikoralston: to get you the stripes (if that's important to you), you could use the ggpattern
package.
# load packages
library(tidyverse)
library(ggpattern)
# make size of step in x vector smaller
x <- seq(0,30,0.1)
y1 <- (60-2*x)/0.8
y2 <- (90-4*x)/0.4
y3 <- (150-6*x)/0.8
df <- tbl_df(data.frame(x,y1,y2,y3)) %>%
# pmax computes the max value of y1, y2, y3 element-wise
mutate(ymin=pmax(y1,y2,y3))
df %>%
ggplot(aes(x=x,y=y1))+
geom_line(y=y1,color="red")+
geom_line(y=y2,color="blue")+
geom_line(y=y3,color="green")+
geom_ribbon_pattern(aes(x=x, ymin=ymin, ymax=Inf),
pattern_color = NA,
pattern_fill = "orange",
pattern = "stripe",
fill = NA,
alpha=0.5) +
ylim(0,225)
Which gets you:
Upvotes: 1
Reputation: 1236
You can use geom_ribbon
for that. You need to create a new column in your dataframe with the y values of the lower bound of the area and map it to the ymin
aesthetics. Since in this case you don't have an upper bound, you can just pass Inf
to ymax
.
Note that this may leave some gaps above the intersection points if they are not explicitly included in the dataframe (this happened to me with your example). To fix this, you could simply add the x values of the intersection points to x
or you could make the step size in x smaller so you will be close enough to the intersection points (this is what I did).
# make size of step in x vector smaller
x <- seq(0,30,0.1)
y1 <- (60-2*x)/0.8
y2 <- (90-4*x)/0.4
y3 <- (150-6*x)/0.8
df <- tbl_df(data.frame(x,y1,y2,y3)) %>%
# pmax computes the max value of y1, y2, y3 element-wise
mutate(ymin=pmax(y1,y2,y3))
df %>%
ggplot(aes(x=x,y=y1))+
geom_line(y=y1,color="red")+
geom_line(y=y2,color="blue")+
geom_line(y=y3,color="green")+
geom_ribbon(aes(x=x, ymin=ymin, ymax=Inf), fill='orange', alpha=0.5) +
ylim(0,225)
Upvotes: 2