r - 如何在 ggplot 中绘制具有可变 bin 宽度的直方图?

标签 r ggplot2

我找到了函数 dhist()ggplot2实现由 Denby and Mallows (2009) 描述的可变宽度直方图的包但我找不到任何使用它的例子。我想用下面的代码来创建
可变仓宽:

x1 <- c(rep(0, 250), rlnorm (1000)) 
x2 <- c(rlnorm(1250)) 
x <- data.frame(x1, x2) 
x.long <- melt(x, measure.vars=c("x1","x2")) 
ggplot(x.long, aes(x=value)) + 
 geom_step(aes(x=value, y=..density.., colour=variable), 
   stat="bin", binwidth=0.2) + 
 coord_cartesian(xlim = c(-1, 15)) 

我怎样才能做到这一点?

注意:我从 ggplot2 google group 交叉发布了这个问题它没有得到答复。如果我在这里得到答案,就会在那里发布,反之亦然

最佳答案

给你,多亏了哈德利的提示和大量的反复试验。我还更改了数据和 bin 数量 ( nbins ),以使效果更加明显。

library(ggplot2) #using version 0.8.8
x1 <- c(rnorm(100,8,4), rnorm(100, 2,2), rnorm(100,0,10))
x2 <- c(rlnorm(1000),rnorm(1000,1,10), rep(1,500), rep(5,500))
ggplot() + 
  geom_step(aes(x1, y =..density..),
            stat = 'bin',breaks = dhist(x1, nbins =20),
            position = "dodge", color = 'red') +
  geom_step(aes(x2, y =..density..),
            stat = 'bin',breaks = dhist(x2,nbins=20),
            position = "dodge", color = 'blue') 

enter image description here

关于r - 如何在 ggplot 中绘制具有可变 bin 宽度的直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5515958/

相关文章:

r - 为什么直接调用 mget() 与在另一个函数中调用 mget() 时,data.table j 有不同的环境?

r - 将 exp/power 趋势线添加到 ggplot

r - R 中的 S 形曲线拟合

r - 如何: Create a plot for 3 categorical variables and a continuous variable in R?

r - 如何反转轴顺序并在 ggplot 中使用预定义的比例?

r - 检测栅格是否在 SpatialPolygons 对象之内、之外或相交

string - 如何使用R的c api分配字符串?

r - 在 ggplot stat_smooth 调用后可以提取模型拟合参数吗?

regex - 提取R中符号周围的字符

r - 在两列相等的数据框中查找行