Normalization x scales of overlaid density plots in ggplot

When overlaying ggplot density graphs that contain data of the same length but at different scales, is it possible to normalize the x scale for the graphs so that the density matches? Alternatively, is there a way to normalize the density scale y?

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!

+3
source share
1 answer

Does it do what you hoped 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 a single data argument will center the empirical distribution by 0 and then divide the resulting values ​​by the standard deviation of the sample so that the result has a standard deviation of 1. You can change the default values ​​for the location and the degree of “compression” or “expansion”. You will probably need to investigate the placement of the corresponding x_scales for y1 and y2. This may require some pre-processing with a scale. The scaling factor is recorded in the attribute of the returned object.

  attr(scale(data$y2), "scaled:scale") #[1] 53.21863 
+4
source

All Articles