Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_area different fill colour when above critical level

Tags:

I am trying to get a geom_area to have twin colours dependant on value of Y axis.

So for example if we have a geom_area with a max X value of 50, I would like the fill colour to be blue when below 10 and red when above 10.

Sample Data;

df <- data.frame(
  y = sample(1:50),
  x = sample(1:50)
)

The closest that I have managed to get thus far is by using the following code;

ggplot(data = df, aes(x = x)) + 
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue")

This almost gets me what I require however the problem is that the horizontal split is not completely across the geom_area, as when the next value falls below the max value the edge of the ribbon goes straight to the next point, which upsets the split.

SamplePlot

This is plotting exactly what the code tells it, so I must be using the wrong method to create the split in colours, but cannot figure out how to do it correctly.

like image 849
redbaron1981 Avatar asked Mar 30 '17 20:03

redbaron1981


1 Answers

A quick fix would be to interpolate between the x-values using approx. Set the n argument (the number of interpolation points) to a high-enough value to get blue all the way across:

ggplot(data = as.data.frame(approx(df,n=1000)), aes(x = x)) + 
  geom_area(aes(y = y),fill = "red") +
  geom_ribbon(aes(ymin = 0, ymax = ifelse(y >= 10,10,y)),fill = "blue") +
  theme_classic()

enter image description here

like image 156
eipi10 Avatar answered Sep 29 '22 23:09

eipi10