4

I want to create a density plot with ridges where colour is conditional on crossing a certain threshold.

The aim is to illustrate the distribution of earnings while highlighting those over a certain threshold (AUD $1368 per week). I've provided a bare-bones plot of my attempt below.

ggplot(subset(vic, totalweekslost > 0 & nwe %in% 100:3000), 
       aes(nwe, fill = nwe > 1368)) + 
  geom_density()

Instead of just changing the colour of those within a single group in the density plot, it creates a new group on its own scale.

reproduced here

What I want is for the colour change to be in the same group and a clear cut-point illustrated. I can see what is wrong with my code, but I can't figure out how to create what I'm after.

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
Tyler Lane
  • 79
  • 1
  • 6
  • 1
    There are numerous similar questions floating around. You may wish to check out [this](https://stackoverflow.com/questions/36224394/shade-density-plot-to-the-left-of-vline) or [this](https://stackoverflow.com/questions/46516759/fixed-fill-for-different-sections-of-a-density-plot-with-ggplot), for example. – Z.Lin Jun 25 '19 at 09:17

1 Answers1

2

Maybe you can get the values of geom_density() and use geom_area().
Reference here
This should do the trick:

library(ggplot2)

# Build some data
vic = data.frame(totalweekslost = 100:3000, nwe = 100:3000)

#Yours code
df = subset(vic, totalweekslost > 0 & nwe %in% 100:3000 )    

# Creating density plot
p = ggplot(df, 
           aes(x = nwe)
          ) + 
  geom_density()

# Getting the values of plot
d = ggplot_build(p)$data[[1]]

# Building shaded area
p = p +  geom_area(data = subset(d, x>1368), aes(x=x,y=y), fill = "#00AFBB", alpha = 0.5)

plot(p)

Here the output plot

vpz
  • 984
  • 1
  • 15
  • 26
  • Great! The link above have another example to this kind of fill. You can add an vertical line in the boundary too, just add: `geom_vline(xintercept = 1368)` . Best regards – vpz Jun 26 '19 at 11:28