ggplot2密度直方图与自定义bin边缘 [英] ggplot2 density histogram with custom bin edges

查看:810
本文介绍了ggplot2密度直方图与自定义bin边缘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以绘制一个密度直方图,并且我可以绘制一个具有自定义框的常规直方图,但不能同时显示在一起。这是我的尝试:

I'm able to plot a density histogram, and I'm able to plot a regular histogram with custom bins, but not both together. Here's my attempt:

library(ggplot2)

vals = c(2.6, 5.2, 4.1, 6.9, 5.7, 5.2, 4.4, 5.5, 6.3, 6.1, 4.7, 1.4)
myplot = qplot(vals, geom = 'blank') +   
         geom_line(aes(y = ..density..), stat = 'density',
                   colour = 26, size = 2, alpha = .6) +                     
         geom_histogram(aes(y = ..density..), binwidth = 1,
                        fill = 28, alpha = 0.3) +
         stat_bin(breaks=seq(-.5,8.5,1)) + xlim(-1, 9)

print(myplot)

如果您删除 stat_bin 作为密度直方图正确绘图,但具有默认的箱位置。添加 stat_bin 项,并且分箱是正确的,但它不再是密度直方图。任何想法如何使两个工作?

If you remove the stat_bin term, the histogram plots correctly as a density histogram, but with default bin locations. Add the stat_bin term, and the bins are correct but it's no longer a density histogram. Any ideas how to get both working?

推荐答案

您可以添加参数 breaks = geom_histogram()来设置您自己的断点(您不必使用 geom_histogram() stat_bin(),因为 geom_histogram()使用 stat_bin()

You can add argument breaks= to the geom_histogram() to set your own break points (you don't have to use geom_histogram() and stat_bin() together because geom_histogram() uses stat_bin() to produce result).

qplot(vals, geom = 'blank') +   
  geom_line(aes(y = ..density..), colour=26, stat = 'density', size = 2, alpha = .6) + 
  geom_histogram(aes(y = ..density..), fill = 28, alpha = 0.3, breaks=seq(-.5,8.5,1))

这篇关于ggplot2密度直方图与自定义bin边缘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆