Tyler Lane
Tyler Lane

Reputation: 89

Conditional fill in a density plot within same group

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.

Upvotes: 5

Views: 4455

Answers (1)

vpz
vpz

Reputation: 1044

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

Upvotes: 2

Related Questions