geom_area different fill colour when above critica

2019-06-25 09:29发布

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.

标签: r ggplot2
1条回答
一夜七次
2楼-- · 2019-06-25 10:01

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

查看更多
登录 后发表回答