【问题标题】:How can I plot a filled histogram and its density with ggplot2?如何使用 ggplot2 绘制填充直方图及其密度?
【发布时间】:2014-02-19 20:18:59
【问题描述】:

我用 ggplot2 创建了这个直方图:

x = rnorm(100,0,150)
df <- data.frame(val=c(x))
ggplot(df, aes(val,..density.., fill = ..x..>100)) + 
  geom_histogram(binwidth=bw.SJ(df$val), colour="black") +
  scale_fill_hue(h=c(115,230))

我想将 pdf 添加到此直方图中,但是当添加下一行时:

geom_density(colour="red", lwd=1) +

这会返回错误:

Error in get(x, envir = this, inherits = inh)(this, ...) : 
  Aesthetics can not vary with a ribbon

提前致谢!

【问题讨论】:

    标签: r plot ggplot2 histogram


    【解决方案1】:

    如果您在 geom_histogram 内指定 fill = ..x..&gt;100) 而不是整个情节,它应该可以工作。您不能在密度上改变填充颜色。

    ggplot(df, aes(val)) + 
      geom_histogram(aes(fill = ..x.. > 100), 
                     binwidth = bw.SJ(df$val), colour = "black") +
      scale_fill_hue(h = c(115, 230)) +
      geom_density(colour = "red", lwd = 1)
    

    【讨论】:

      【解决方案2】:

      它在密度调用中没有任何参数就可以工作吗?如果是这样试试

      geom_density(colour="red", size=1) +
      

      而不是

      geom_density(colour="red", lwd=1) +
      

      如果这不起作用,一个可重现的示例可能会有所帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-02-23
        • 2018-06-11
        • 2014-08-20
        • 1970-01-01
        • 2012-06-22
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多