简体   繁体   English

在 ggplot2 中绘制直方图

[英]Plot a histogram in ggplot2

want to replicate that here with my data想用我的数据在这里复制

Plot histograms over factor variables 绘制因子变量的直方图

my data look like that我的数据看起来像那样

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

the full data frame is here https://www.dropbox.com/s/r616tyr17q40x6g/t4.RData?dl=0完整的数据框在这里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.第一列是直方图编号,接下来是 bin,最后一列是每个 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]

The bins are the same for every histogram.每个直方图的 bin 都是相同的。 Histogram 1 to 1598 all have 60 bins which range from -11 to plus 2 by 0.2.直方图 1 到 1598 都有 60 个区间,范围从 -11 到加 2 乘以 0.2。 This is in col 2. The specific count is in col 3 and the ind is in col 1.这是在第 2 列中。特定计数在第 3 列中,索引在第 1 列中。

I then do然后我做

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

when i plot pi get当我绘制 pi 时

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

for every histogram.对于每个直方图。

Why do I get that error>为什么我会收到那个错误>

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/我如何摆脱代码中绘制的每个直方图的大标题 - 在我的情况下,它看起来像http://postimg.org/image/4yhvz9i67/

For some reason, your V2 and V3 columns are factors.出于某种原因,您的V2V3列是因子。 Just run赶紧跑

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

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.首先弄清楚为什么它们是因素是个好主意,也许您必须调整函数以将数据读入 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.它将尝试创建 1599 个面,这对我来说在实际绘制之前冻结了 R 会话。

After that I got the following plot:之后我得到了以下情节:

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM