【问题标题】:Overlapping ggplot2 histograms with different variables用不同的变量重叠 ggplot2 直方图
【发布时间】:2014-06-22 05:07:53
【问题描述】:

如果我有 2 个不同的变量要绘制为直方图,我会怎么做?举个例子:

data1 <- rnorm(100)
data2 <- rnorm(130)

如果我想在同一个图中显示 data1 和 data2 的直方图,有没有办法做到这一点?

【问题讨论】:

    标签: r ggplot2 histogram


    【解决方案1】:

    您可以通过添加另一个geom_histogram 层将它们放在同一个图中:

    ## Bad plot
    ggplot() + 
      geom_histogram(aes(x=data1),fill=2) + 
      geom_histogram(aes(x=data2)) 
    

    不过,更好的办法是使用密度图:

    d = data.frame(x = c(data1, data2), 
                   type=rep(c("A", "B"), c(length(data1), length(data2))))
    ggplot(d) + 
      geom_density(aes(x=x, colour=type))
    

    或方面:

    ##My preference
    ggplot(d) + 
      geom_histogram(aes(x=x)) + 
      facet_wrap(~type)
    

    或使用条形图(感谢@rawr)

    ggplot(d, aes(x, fill = type)) + 
      geom_bar(position = 'identity', alpha = .5)
    

    【讨论】:

    • 另外,位置 = 身份:ggplot(d, aes(x, fill = type)) + geom_bar(position = 'identity', alpha = .5)
    • 谢谢(并添加到答案中)
    【解决方案2】:

    @csgillespie 的回答略有变化和补充:

    ggplot(d) + 
      geom_density(aes(x=x, colour=type, fill=type), alpha=0.5)
    

    给出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多