Mas*_*013 6 r histogram ggplot2
我有以下数据
dati <- read.table(text="
class num
1 0.0 63530
2 2.5 27061
3 3.5 29938
4 4.5 33076
5 5.6 45759
6 6.5 72794
7 8.0 153177
8 10.8 362124
9 13.5 551051
10 15.5 198634
")
Run Code Online (Sandbox Code Playgroud)
我想生成一个具有可变大小区间的直方图,以便每个条形区域反映每个区间的总数(num).我试过了
bins <- c(0,4,8,11,16)
p <- ggplot(dati) +
geom_histogram(aes(x=class,weight=num),breaks = bins)
Run Code Online (Sandbox Code Playgroud)
然而,这产生直方图,其中每个条的长度等于每个箱的总数.因为箱宽度是可变的,所以区域与数量不成比例.我无法在ggplot2中解决这个明显容易出问题的问题.谁能帮我?
我认为您正在寻找密度图 -这个密切相关的问题有大部分答案。你打y = ..density..
进来geom_histogram()
。
这是有效的,因为stat_bin
(recall geom_histogram()
is geom_bar()
+ stat_bin()
,并stat_bin()
构造了一个包含列count
和的数据框density
。因此调用会y = ..density..
拉出正确的列密度,而默认值 (counts) 就像您调用y = ..count..
.
##OP's code
ggplot(dati) + geom_histogram(aes(x=class, weight=num),
breaks = bins)
Run Code Online (Sandbox Code Playgroud)
##new code (density plot)
ggplot(dati) + geom_histogram( aes(x=class,y = ..density.., weight=num),
breaks = bins, position = "identity")
Run Code Online (Sandbox Code Playgroud)
你可以找到一些进一步的例子在线GGPLOT2帮助页面的geom_histogram()
。
归档时间: |
|
查看次数: |
6806 次 |
最近记录: |