2015-06-20 64 views
0

我正在創建一個構面網格。我試圖根據指定構面變量(。〜Order)的級別顛倒x軸(Context)上的級別順序。 (例如,對於Order,如果「NFF」,那麼Context的順序=「NF」,「IF」;如果是「IFF」,則Context的順序=「IF」,「NF」)。基於Facet變量重新排序X變量

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的第二個圖形。

+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面板已切換。

+0

非常感謝!這是訣竅! – Dev15

+0

有關如何反轉x軸刻度標籤的想法?我一直在搜索沒有運氣。如果沒有,或許網格安排或類似的會比我的目的方面更好。 – Dev15

+0

使用gridExtra結束。更容易處理逆轉。 – Dev15