prideloki -4 years ago 165
R Question

# How can i add two shade on both end of the density distribution plot

How can i add shaded on both end like the picture below?

i want to add one end from 0 to -.995 and 1.995 to Inf

I tried solution here http://stackoverflow.com/a/4371473/3133957 but it doesn't seem to work.

here my code

``````tmpdata <- data.frame(vals = t.stats)
qplot(x = vals,  data=tmpdata, geom="density",
xlab="sampling distribution of t-statistic",
ylab="frequency") +
geom_vline(xintercept = t.statistic(precip, population.precipitation),
linetype = "dashed") +
geom_ribbon(data=subset(tmpdata,vals>-1.995 & vals<1.995),aes(ymax=max(vals),ymin=0,fill="red",alpha=0.5))
``````

You didn't provide a dataset for your question, so I simulated one to use for this answer. First, make your density plot:

``````tmpdata <- data.frame(vals = rnorm(10000, mean = 0, sd = 1))
plot <- qplot(x = vals,  data=tmpdata, geom="density",
xlab="sampling distribution of t-statistic",
ylab="frequency")
``````

Then, extract the x and y coordinates used by ggplot to plot your density curve:

``````area.data <- ggplot_build(plot)\$data[[1]]
``````

You can then add two `geom_area` layers to shade in the left and right tails of your curve via:

``````plot +
geom_area(data=area.data[which(area.data\$x < -1.995),], aes(x=x, y=y), fill="skyblue") +
geom_area(data=area.data[which(area.data\$x > 1.995),], aes(x=x, y=y), fill="skyblue")
``````

This will give you the following plot:

Note that you can add your `geom_vline` layer after this (I left it out because it required data you did not supply in your question).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download