2012-10-22 152 views
2

此代碼非常小,應該能夠調整爲解決方案。ggplot2 - 在堆積條形圖中翻轉水平的排序

blah <- data.frame(X1=c("Decrease Risk","Don't Know","Increase Risk","No Effect","Decrease Risk","Don't Know","Increase Risk","No Effect"), 
        X2=c("Red Meat","Red Meat","Red Meat","Red Meat","Red Meat","Red Meat","Red Meat","Red Meat"), 
        value=c(1.98,31.19,64.38,2.43,4.65,24.55,35.88,34.90), 
        status=c("Case","Case","Case","Case","Control","Control","Control","Control") 
        ) 

ggplot(blah, aes(X2, value, fill=X1)) + geom_bar() + coord_flip() + facet_wrap(~status) + 
    labs(x="Perceived Risk Factors", y="Percentage (%)", tilte="Some Title", fill="Responses") 

enter image description here

我想的是,在右側的「控制」有「迴應」的級別的順序顛倒。重點是控制紫色是在裏面,然後是藍色的,然後在外面是綠色和粉紅色。在這樣的情節中做這件事很常見,我可以想辦法做到這一點,其中涉及一些相當髒的變量重複和有序因素水平的變化,但認爲某人可能有一個優雅的解決方案/想法?

回答

3

這是一個使用順序美學的微妙方法。

ggplot(blah, aes(X2, value, fill = X1, 
    order = (3-as.numeric(status)*2) * as.numeric(X1))) + 
geom_bar() + coord_flip() + facet_wrap(~status) + 
labs(x="Perceived Risk Factors", y="Percentage (%)", title="Some Title", 
    fill="Responses") 

enter image description here

,因爲它並不能一概而論所有容易,當有兩個以上的方面是不理想的。

+0

這很酷。因爲公平,「反射」型着色(我曾想過)只會在面上有兩組時使用。謝謝,我需要自己加快排序。 – nzcoops