在ggplot2中绘制直方图 [英] Plot a histogram in ggplot2

查看:76
本文介绍了在ggplot2中绘制直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想在这里用我的数据复制

want to replicate that here with my data

在因子变量上绘制直方图

我的数据看起来像这样

2 -11.0  0
2 -10.8  0
2 -10.6  0
2 -10.4  0
2 -10.2  0

完整的数据框架在此处 https://www.dropbox.com/s/r616tyr17q40x6g/t4.RData?dl = 0

the full data frame is here https://www.dropbox.com/s/r616tyr17q40x6g/t4.RData?dl=0

第一列是直方图编号,第二列是垃圾箱,最后一列是每个垃圾箱的计数.与原始示例中一样(工作日,小时,计数).

the first column is the histogram number, the next is the bins an d the last is the counts per vi bin. As in the original example (weekday,hours,count).

我也将列考虑在内-因为我没有字符串,我只是这样做

I also factor the columns - as i dont have strings I just do

as.factor(df[,3])-.df[,3]
asfactor(df[,2])->df[,2]

每个直方图的垃圾箱都相同.直方图1到1598都具有60个bin,范围从-11到加2乘0.2.它在第2列中.具体计数在第3列中,而ind在第1列中.

The bins are the same for every histogram. Histogram 1 to 1598 all have 60 bins which range from -11 to plus 2 by 0.2. This is in col 2. The specific count is in col 3 and the ind is in col 1.

然后我就做

p<-ggplot(data=t4, aes(x=V2))
p<-p+geom_histogram(aes(weights=V3))
p<-p+facet_wrap(~V1,ncol=1)

当我绘制p时

Error in Summary.factor(structure(1L, .Label = c("0", "1", "2", "3", "4",  : 
  sum not meaningful for factors

对于每个直方图.

为什么会出现该错误>

Why do I get that error>

对于代码中绘制的每个直方图,我还应该如何摆脱较大的标头-在我的情况下,它看起来像那样 http://postimg.org/image/4yhvz9i67/

how owuld I also get rid of the large header for every histogram plotted in the code - in my case it would look like that http://postimg.org/image/4yhvz9i67/

推荐答案

由于某些原因,您的 V2 V3 列是重要因素.刚运行

For some reason, your V2 and V3 columns are factors. Just run

t4$V2 <- as.numeric(t4$V2)
t4$V3 <- as.numeric(t4$V3)

此问题将得到解决.弄清楚为什么它们是首先要考虑的因素是一个好主意,也许您需要调整功能才能将数据读入R.

And this problem will be solved. It's a good idea to figure out why they were factors in first place, maybe you'll have to adjust your function to read the data into R.

不过,我认为您不希望以这种方式使用这些方面.它将尝试创建1599个构面,对我而言,这些构面在实际绘制之前已冻结了R会话.

I don't think you want to to use the facets this way though. It will try to create 1599 facets which for me froze the R session before it actually plotted.

此后,我得到了以下情节:

After that I got the following plot:

library(ggplot2)
ggplot(data=t4, aes(x=V2)) + geom_histogram(aes(weights=V3))

这篇关于在ggplot2中绘制直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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