Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Normalising the x scales of overlaying density plots in ggplot

Tags:

r

ggplot2

When overlaying ggplot density plots that feature data of same length but different scales is it possible to normalise the x scale for the plots so the densities match up? Alternatively is there a way to normalise the density y scale?

enter image description here

library(ggplot2)

data <- data.frame(x = c('A','B','C','D','E'), y1 = rnorm(100, mean = 0, sd = 1), 
               y2 = rnorm(100, mean = 0, sd = 50))
p <- ggplot(data)

# Overlaying the density plots is a fail
p + geom_density(aes(x=y1), fill=NA) + geom_density(aes(x=y2), alpha=0.3,col=NA,fill='red')

# You can compress the xscale in the aes() argument:
y1max <- max(data$y1)
y2max <- max(data$y2)
p + geom_density(aes(x=y1), fill=NA) + geom_density(aes(x=y2*y1max/y2max), alpha=0.3,col=NA,fill='red')
# But it doesn't fix the density scale. Any solution?

# And will it work with facet_wrap?
p + geom_density(aes(x=y1), col=NA,fill='grey30') + facet_wrap(~ x, ncol=2)

Thanks!

like image 943
geotheory Avatar asked Dec 13 '25 12:12

geotheory


1 Answers

Does this do what you were hoping for?

p + geom_density(aes(x=scale(y1)), fill=NA) + 
    geom_density(aes(x=scale(y2)), alpha=0.3,col=NA,fill='red')

The scale function with only a single data argument will center an empiric distribution on 0 and then divide the resulting values by the sample standard deviation so the result has a standard deviation of 1. You can change the defaults for the location and the degree of "compression" or "expansion". You will probably need to investigate putting in appropriate x_scales for y1 and y2. This may take some preprocessing with scale. The scaling factor is recorded in an attribute of the returned object.

 attr(scale(data$y2), "scaled:scale")
#[1] 53.21863
like image 179
IRTFM Avatar answered Dec 15 '25 01:12

IRTFM



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!