ggplot facets中的单独排序

时间:2012-07-06 14:37:39

标签: r ggplot2

所以我有一个简单的例子 - 一个完全交叉的三个治疗三个背景实验,其中测量每个治疗上下文对的连续效应。我想根据每种情况分别按照效果订购每种治疗方法,但我仍然坚持使用ggplot的方法。

这是我的数据

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 个答案:

答案 0 :(得分:4)

Faceting并不是您想要做的正确工具,因为它真的是为共享比例的情况设计的。

将每个绘图分开制作然后使用 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

答案 1 :(得分: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))
相关问题