Multiple histograms in ggplot2

前端 未结 2 1903
走了就别回头了
走了就别回头了 2020-12-06 02:14

Here is a short part of my data:

dat <-structure(list(sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L),          


        
相关标签:
2条回答
  • 2020-12-06 02:38

    To follow up on chl's example - here's how to duplicate your base graphic with ggplot. I would heed his advice in looking to dotplots as well:

    library(ggplot2)
    dat.m <- melt(dat, "sex") 
    
    ggplot(dat.m, aes(value)) + 
      geom_bar(binwidth = 0.5) + 
      facet_grid(variable ~ sex)
    
    0 讨论(0)
  • 2020-12-06 02:50

    You can try grid.arrange() from the gridExtra package; i.e., store your plots in a list (say qplt), and use

    do.call(grid.arrange, qplt)
    

    Other ideas: use facetting within ggplot2 (sex*variable), by considering a data.frame (use melt).

    As a sidenote, it would be better to use stacked barchart or Cleveland's dotplot for displaying items response frequencies, IMO. (I gave some ideas on CrossValidated.)


    For the sake of completeness, here are some implementation ideas:

    # simple barchart
    ggplot(melt(dat), aes(x=as.factor(value), fill=as.factor(value))) + 
      geom_bar() + facet_grid (variable ~ sex) + xlab("") + coord_flip() + 
      scale_fill_discrete("Response")
    

    enter image description here

    my.df <- ddply(melt(dat), c("sex","variable"), summarize, 
                   count=table(value))
    my.df$resp <- gl(3, 1, length=nrow(my.df), labels=0:2)
    
    # stacked barchart
    ggplot(my.df, aes(x=variable, y=count, fill=resp)) + 
      geom_bar() + facet_wrap(~sex) + coord_flip()
    

    enter image description here

    # dotplot
    ggplot(my.df, aes(x=count, y=resp, colour=sex)) + geom_point() + 
      facet_wrap(~ variable)
    

    enter image description here

    0 讨论(0)
提交回复
热议问题