首页 文章

ggplot facets中的单独排序

提问于
浏览
8

所以我有一个简单的例子 - 一个完全交叉的三个治疗三个上下文实验,其中测量每个治疗上下文对的连续效果 . 我想根据每种情况分别按照效果对每种治疗方式进行排序,但我要分面 .

这是我的数据

df <- data.frame(treatment = rep(letters[1:3], times = 3),
                 context = rep(LETTERS[1:3], each = 3),
                 effect = runif(9,0,1))

如果我将治疗和背景分解为单个9分制,我可以得到非常接近的东西,如下:

df$treat.con <- paste(df$treatment,df$context, sep = ".")
df$treat.con <- reorder(df$treat.con, -df$effect, )

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

very close to what i want

除了在每个方面实现单独排序之外,我创建的新x变量可能具有误导性,因为它没有证明我们在所有三个上下文中都使用了相同的处理方式 .

这是通过对潜在因素的一些操纵来解决的,还是有针对这种情况的ggplot命令?

2 回答

  • 4

    尝试:

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

    提供给 labels 参数的匿名函数执行标签的格式化 . 在旧版本的ggplot2中,您使用了 formatter 参数 . 如果您的治疗名称长度不同,那么 substr 方法可能效果不好,但您可以使用 strsplit ,例如:

    + scale_x_discrete(labels=function(x) sapply(strsplit(x,"[.]"),"[",1))
    
  • 4

    Faceting isn 't really the right tool for what you want to do, since it' s真正适用于具有共享比例的情况 .

    将每个绘图分开制作然后使用 gridExtra 包中的 grid.arrange 进行排列可能更有意义 . (请注意,如果您不熟悉这些工具,以下代码可能看起来有点难以理解!)

    #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

相关问题