在ggplot方面分开排序 [英] Separate ordering in ggplot facets

查看:152
本文介绍了在ggplot方面分开排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个简单的例子 - 一个完全交叉的三个治疗三个上下文实验,其中每个治疗上下文对的连续效应被测量。我想按照每种情况分别对每种治疗方式进行排序,但我坚持使用ggplot的方法。



这里是我的数据

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


$ b $如果我把治疗和背景分解为单一的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)



除了实现th在每个方面单独排序,我创建的新x变量可能会产生误导,因为它没有证明我们在所有三种情况下都使用了相同的处理方法。



这是通过一些基本因素的操纵来解决的,或者是否存在针对这种情况的ggplot命令?解析方案

试试:

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

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

  + scale_x_discrete(labels = function(x)sapply(strsplit(x,[。]), [,1))


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 to order each treatment by effect, separately according for each context, but I'm stuck on ggplot's faceting.

here's my data

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

and I can get something very close if I collapse treatment and context into a single 9 point scale, as such:

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)

except to achieve the separate ordering in each facet, the new x variable I created is potentially misleading, since it doesn't demonstrate that we've used the same treatment in all three contexts.

Is this solved via some manipulation of the underlying factor, or is there a ggplot command for this situation?

解决方案

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

这篇关于在ggplot方面分开排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆