multiple graphs in one canvas using ggplot2

后端 未结 3 1248
失恋的感觉
失恋的感觉 2020-11-28 05:34

I am trying to merge two ggplot2 plots into one based on this table:

   Type    RatingA  RatingB
1  One     3        36
2  Two     5        53
3  One     5           


        
3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-28 06:06

    Julio,

    You mention that p1 and p2 have the same x-axis, but the reordering you do based on mean does not make them the same. p1's axis goes "one --> two --> three" while p2's axis goes "two --> one --> three". Is this intentional?

    Regardless, ggplot offers a few other solutions to combine these plots into one, namely colour and faceting (which you may have already tried?). The first step to either of these is to melt your data.frame to long format. We will identify the id variable "Type" and melt assumes the rest of the columns are to be melted.

    test.m <- melt(test, id.var = "Type")
    

    A quick check of the structure of the new object indicates most everything is in line, except the levels for type are a bit out of whack:

    > str(test.m)
    'data.frame':   12 obs. of  3 variables:
     $ Type    : Factor w/ 3 levels "One","Three",..: 1 3 1 1 2 2 1 3 1 1 ...
     $ variable: Factor w/ 2 levels "RatingA","RatingB": 1 1 1 1 1 1 2 2 2 2 ...
     $ value   : int  3 5 5 7 4 8 36 53 57 74 ...
    

    So let's rearrage the levels:

    test.m$Type <- factor(test.m$Type, c("One", "Three", "Two"), c("One", "Two", "Three"))
    

    Now for the plotting. With colour:

    ggplot(test.m, aes(x = Type, y = value, group = variable, colour = variable)) + 
    stat_summary(fun.y = "mean", geom = "point") 
    

    or with facets:

    ggplot(test.m, aes(x = Type, y = value, group = variable)) + 
    stat_summary(fun.y = "mean", geom = "point") +
    facet_grid(variable ~ ., scales = "free")
    

    Note I used the scales = "free" argument in the faceting so that each plot has its' own scale. Simply remove that argument if that's not the effect you want.

提交回复
热议问题