Normalising the x scales of overlaying density plo

2019-05-11 23:37发布

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!

标签: r ggplot2
1条回答
再贱就再见
2楼-- · 2019-05-12 00:00

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
查看更多
登录 后发表回答