【问题标题】:Reorder X variable based on Facet variable基于 Facet 变量重新排序 X 变量
【发布时间】:2015-06-20 03:59:54
【问题描述】:

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

(例如,对于 Order,如果为“NFF”,则 Context 的顺序 = “NF”、“IF”;如果为“IFF”,则 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 的顺序。

【问题讨论】:

  • 请将此展示给您的一位同事,看看他们是否能理解此请求。也许他们可以帮助您编辑它,以便我们其他人可以理解地阅读它。

标签: r ggplot2 facet


【解决方案1】:

您可以通过创建一个虚拟变量来做到这一点,该变量是 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")

此处的目标是仅在“Premium”方面更改此图中的清晰度顺序(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")

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

【讨论】:

  • 关于如何反转 x 轴刻度标签的任何想法?我一直在寻找没有运气。如果没有,也许网格排列或类似的东西会比我的目的更好。
  • 最终使用了 gridExtra。更容易处理逆转。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-07
  • 2018-06-05
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多