How to obscure part of the density curve in ggplot (without y axis data)

I am trying to create a density curve in R using a set of random numbers between 1000, and obscures the part that is less than or equal to a specific value. There are many solutions involving geom_area or geom_ribbon , but all of them require yval , which I don’t have (this is just a vector of 1000 numbers). Any ideas on how I can do this?

Two other related questions:

  • Is it possible to do the same for the cumulative density function (I am currently using stat_ecdf to create it) or not shade it at all?
  • Is there a way to edit geom_vline , so it will only go up to the height of the density curve, and not the entire y axis?

Code: ( geom_area is an unsuccessful attempt to edit some code that I found. If I install ymax manually, I just get a column occupying the entire graph, not just the area under the curve)

 set.seed(100) amount_spent <- rnorm(1000,500,150) amount_spent1<- data.frame(amount_spent) rand1 <- runif(1,0,1000) amount_spent1$pdf <- dnorm(amount_spent1$amount_spent) mean1 <- mean(amount_spent1$amount_spent) #density/bell curve ggplot(amount_spent1,aes(amount_spent)) + geom_density( size=1.05, color="gray64", alpha=.5, fill="gray77") + geom_vline(xintercept=mean1, alpha=.7, linetype="dashed", size=1.1, color="cadetblue4")+ geom_vline(xintercept=rand1, alpha=.7, linetype="dashed",size=1.1, color="red3")+ geom_area(mapping=aes(ifelse(amount_spent1$amount_spent > rand1,amount_spent1$amount_spent,0)), ymin=0, ymax=.03,fill="red",alpha=.3)+ ylab("")+ xlab("Amount spent on lobbying (in Millions USD)")+ scale_x_continuous(breaks=seq(0,1000,100)) 
+5
source share
1 answer

There are a few questions that show this ... here and here , but they calculate the density before drawing the picture.

This is another way, more complex than required, which allows ggplot to do some calculations for you.

 # Your data set.seed(100) amount_spent1 <- data.frame(amount_spent=rnorm(1000, 500, 150)) mean1 <- mean(amount_spent1$amount_spent) rand1 <- runif(1,0,1000) 

Basic Density Chart

 p <- ggplot(amount_spent1, aes(amount_spent)) + geom_density(fill="grey") + geom_vline(xintercept=mean1) 

You can select the x and y positions for the shadow in the area from the chart object using ggplot_build . Linear interpolation was used to get the y value at x=rand1

 # subset region and plot d <- ggplot_build(p)$data[[1]] p <- p + geom_area(data = subset(d, x > rand1), aes(x=x, y=y), fill="red") + geom_segment(x=rand1, xend=rand1, y=0, yend=approx(x = d$x, y = d$y, xout = rand1)$y, colour="blue", size=3) 

enter image description here

+8
source

All Articles