简体   繁体   中英

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

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]

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.

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

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/

For some reason, your V2 and V3 columns are factors. 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.

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))

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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