Separate ordering in ggplot facets

前端 未结 2 1600
后悔当初
后悔当初 2020-12-16 21:45

so I have a simple example--a fully crossed three treatmentthree context experiment, where a continuous effect was measured for each treatmentcontext pair. I want t

相关标签:
2条回答
  • 2020-12-16 22:34

    Faceting isn't really the right tool for what you want to do, since it's really designed for situations with shared scales.

    It might make more sense to make each plot separately and then arrange them each using grid.arrange from the gridExtra package. (Be warned, the following code might seem a bit inscrutable if you're not familiar with these tools!)

    #I use stringsAsFactors simply to ensure factors on
    # my system.
    df <- data.frame(treatment = rep(letters[1:3], times = 3),
                     context = rep(LETTERS[1:3], each = 3),
                     effect = runif(9,0,1),stringsAsFactors = TRUE)
    
    require(gridExtra)
    #One "master" plot (to rule them all)
    p <- ggplot(df,aes(x = treatment,y = effect)) + 
            geom_point() + 
            facet_wrap(~context)
    
    #Split data set into three pieces    
    df_list <- split(df,df$context)
    #...and reorder the treatment variable of each one
    df_list <- lapply(df_list,function(x){x$treatment <- reorder(x$treatment,-x$effect); x})
    
    #"Re-do" the plot p using each of our three smaller data sets
    # This is the line that might be the most mysterious            
    p_list <- lapply(df_list,function(dat,plot){plot %+% dat},plot = p)
    
    #Finally, place all three plots on a single plot
    do.call(grid.arrange,p_list)
    

    enter image description here

    0 讨论(0)
  • 2020-12-16 22:47

    Try:

    ggplot(df, aes(x = treat.con, y = effect)) +
      geom_point() +
      facet_wrap(~context, scales="free_x", ncol = 1) +
      scale_x_discrete(labels=function(x) substr(x,1,1))
    

    The anonymous function provided to the labels argument does the formatting of the labels. In older versions of ggplot2 you used the formatter argument for this. If your treatment names are of differing lengths, then the substr approach might not work too well, but you could use strsplit, eg:

    + scale_x_discrete(labels=function(x) sapply(strsplit(x,"[.]"),"[",1))
    
    0 讨论(0)
提交回复
热议问题