根据Facet变量重新排序X变量

时间:2015-06-20 03:59:55

标签: r ggplot2 facet

我正在创建一个构面网格。我试图根据指定的facet变量(.~Order)的级别来反转x轴(Context)上的级别顺序。

(例如,对于订单,如果" NFF",那么Context的顺序=" NF"," IF&#34 ;; if" IFF&#34 ;然后是Context的顺序=" IF"," NF")。

修改我正在使用的数据:

Order <- c("NFF", "NFF", "NFF", "NFF", "IFF", "IFF", "IFF", "IFF")
Concept <- c("BT","BT", "H", "H", "BT", "BT", "H", "H")
Context <- c("NF", "IF", "NF", "IF", "IF", "NF", "IF", "NF")
Mean <- c(3.587, 3.857, 3.467, 3.101, 2.986, 3.965, 3.154, 3.555)
SE <- c(0.13, 0.229, 0.143, 0.251, 0.281, 0.159, 0.251, 0.143)

FlowExp1 <- data.frame(Order, Concept, Context, Mean, SE)

到目前为止我的尝试:

FlowExp1$Context <- factor(FlowExp1.3$Context,
                   levels = c("No Friction", "Implied Friction"))

limits <- aes(ymax = Mean + SE, ymin=Mean - SE)
dodge <- position_dodge(width=0.5)
cb<- c("dark grey", "grey30")

p <- ggplot(FlowExp1, aes(fill=Concept, y=Mean, x=Context))
p2<- p + geom_bar(position="dodge", stat="identity", width = .5)


p2 + 
  geom_bar(position=dodge) + 
  scale_fill_manual(values=cb, guide = FALSE)+
  geom_errorbar(limits, position=dodge, width=0.25) + 
  ylim(0,5) +
  facet_grid(. ~ Order)

这几乎可以工作,我只需要在facet_grid的第二个图形上反转Context的顺序。

1 个答案:

答案 0 :(得分:0)

你可以通过创建一个虚拟变量来实现这一点,该变量是x轴上的变量和你所面对的变量之间的interaction

library(ggplot2)

## Use a subset of the diamonds dataset
data(diamonds)
dat <- droplevels(with(diamonds, diamonds[color %in% c("E","I") & 
                                 clarity %in% c("SI2", "SI1"), ]))

## See what it looks like first
p <- ggplot(dat, aes(fill=color, y=carat, x=clarity))
p2 <- p + geom_bar(position="dodge", stat="identity", width=0.5)
p2 + facet_grid(. ~ cut, scales="free_x")

enter image description here

此处的目标是仅在“高级”方面更改此图中的清晰度顺序(x轴)。

## Create a new factor of the interactions between variables of interest
dat$fact <- with(dat, interaction(cut, clarity))

## Change the order of clarity in "Premium" facet only
inds <- levels(dat$fact)
inds[grep("Premium", inds)] <- rev(grep("Premium", inds, value=T))
dat$fact <- factor(dat$fact, levels=inds)

## Plot it
p <- ggplot(dat, aes(fill=color, y=carat, x=fact))
p2 <- p + geom_bar(position="dodge", stat="identity", width=0.5)
p2 + facet_grid(. ~ cut, scales="free_x") +
  scale_x_discrete(labels="") + xlab("Clarity")

enter image description here

请注意,SI2和SI1的顺序已在Premium面板中切换。