【问题标题】:Normalising the x scales of overlaying density plots in ggplot规范化ggplot中覆盖密度图的x尺度
【发布时间】:2012-09-08 14:01:56
【问题描述】:

当覆盖具有相同长度但不同比例的特征数据的 ggplot 密度图时,是否可以标准化图的 x 比例以使密度匹配?或者有没有办法标准化密度y尺度?

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)

谢谢!

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    这是否符合您的期望?

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

    只有一个数据参数的scale 函数将使经验分布以 0 为中心,然后将结果值除以样本标准差,因此结果的标准差为 1。您可以更改位置的默认值以及“压缩”或“膨胀”的程度。您可能需要调查为 y1 和 y2 设置适当的 x_scales。这可能需要一些规模的预处理。缩放因子记录在返回对象的属性中。

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

    【讨论】:

    • 是的。多么简单!谢谢@DWin
    猜你喜欢
    • 2018-11-26
    • 1970-01-01
    • 2014-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-02
    • 2015-10-16
    • 2010-09-22
    相关资源
    最近更新 更多