ggplot facets中的单独排序

tom*_*omw 8 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))
Run Code Online (Sandbox Code Playgroud)

如果我将治疗和背景分解为单个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)
Run Code Online (Sandbox Code Playgroud)

非常接近我想要的

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

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

jor*_*ran 5

构面并不是真正适合您要做什么的工具,因为它确实是为具有共享尺度的情况而设计的。

它可能会更有意义分别使每个情节,然后安排他们分别使用grid.arrangegridExtra包。(请注意,如果您不熟悉以下工具,则以下代码可能看起来有点难以理解!)

#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)
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Jam*_*mes 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))
Run Code Online (Sandbox Code Playgroud)

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

+ scale_x_discrete(labels=function(x) sapply(strsplit(x,"[.]"),"[",1))
Run Code Online (Sandbox Code Playgroud)