在R:空栅格中叠加直方图

时间:2014-11-01 01:01:24

标签: r ggplot2 histogram

我试图为不同的子组堆叠直方图。这是我的data.table:

> head(result)
     persnr year     diff
1: 61961225 1994 22.52241
2: 62037645 1994 22.52241

这是结构:

> str(result)
Classes ‘data.table’ and 'data.frame':  25213 obs. of  3 variables:
 $ persnr: num  61961225 62037645 62181514 62499451 62649247 ...
 $ year  : int  1994 1994 1994 1994 1994 1994 1994 1994 1994 1994 ...
 $ diff  : num  22.5 22.5 22.5 22.5 22.5 ...
 - attr(*, ".internal.selfref")=<externalptr> 

我尝试创建重叠的直方图,其中year标识子组。我尝试遵循两个不同的答案:[1][2],但两者都会导致相同的错误 - 这不是可谷歌的。我的数据有什么问题/我需要适应什么?

> ggplot(result, aes(x=diff, fill=year)) + geom_histogram(position='identity')
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
Error in grid.Call.graphics(L_raster, x$raster, x$x, x$y, x$width, x$height,  : 
  Empty raster

ggplot(result) + geom_histogram(aes(x=diff, fill=year), position='dodge')
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
Error in grid.Call.graphics(L_raster, x$raster, x$x, x$y, x$width, x$height,  : 
  Empty raster

1 个答案:

答案 0 :(得分:1)

错误消息提示连续的组变量。将它去除它可以解决这个问题:

ggplot(result, aes(x=diff, fill=factor(year))) + geom_histogram(position='identity')