Ben Richards
Ben Richards

Reputation: 33

Shade Under a Line in ggplot2

I am making a simple graph using ggplot2. What I would like to do, is color the area under the graph. One color to the left of the line and one color to the right of the line.

Current code:

ggplot(data=df, aes(x=Price, y=Number_of_Customers, group=1, color=Dmerch)) +
  geom_line(color="#FFC300", size=1)+
  labs(x="Price", y="Number of Customers", title="Willingness to Pay")+
  geom_vline(xintercept=10.84,linetype="solid",size=1, color="#FF5733")+

Graph it makes

enter image description here

Upvotes: 0

Views: 770

Answers (1)

Zhiqiang Wang
Zhiqiang Wang

Reputation: 6769

I would try to separate your Y variable Number_of_Customers into two variables y1 and y2, and then use geom_area to plot separate areas with different colors:

df <- df %>% 
  mutate(y1 = ifelse(Price>=10.84, Number_of_Customers, NA), 
         y2 = ifelse(Price<10.84, Number_of_Customers, NA))  

ggplot(data=df, aes(x=Price,group=1)) +
  geom_area(aes(y = y1), color="blue", fill= "blue", size=1)+
  geom_area(aes(y = y2), color="red", fill= "red", size=1)+
  labs(x="Price", y="Number of Customers", title="Willingness to Pay")+
  geom_vline(xintercept=10.84,linetype="solid",size=1, color="#FF5733")

Upvotes: 2

Related Questions