2017-12-02 239 views
-1

我想創建一個帶有ggplot2的盒圖,並且我想按照數據框的順序組織圖,帶ggplot的盒子圖和傳說標籤的順序

我知道R按字母順序組織boxplot。我怎樣才能:

  1. 組織X軸的順序味道 - 顏色 - 容量
  2. 開關盒子,即第一綠色,然後橙色,而不是橙色和綠色
  3. 交換機傳說階也,第一NaCl和然後O_ {2}
library(ggplot2) 
library(readxl) 

Chemical <- rep(c("NaCl", "Al2"), times = 3, each = 4) 
Quality <- rep(c("Taste", "Color of package", "Capacity"), times = 1, each = 8) 
Accepted <- seq(0, 100, by = 100/23) 

DF <- data.frame(Chemical, Quality, Accepted) 

ggplot(DF, aes(x = Quality, y = Accepted, fill = Chemical)) + 
    geom_boxplot() + 
    scale_fill_manual(values = c("orange", "green"), 
        labels = expression("Al"[2], "NaCl")) + 
    xlab("") + 
    theme(legend.position = "top", legend.title = element_blank()) 

enter image description here

回答

0

您有不同的方法來控制輸出。一個快速的解決方案是:

ggplot(DF, aes(x = Quality, y = Accepted, fill = Chemical)) + 
geom_boxplot() + 
scale_fill_manual(values = c("green", "orange"), 
       labels = expression("Al"[2], "NaCl")) + 
xlab("") + 
theme(legend.position = "top", legend.title = element_blank()) + 
guides(fill=guide_legend(reverse=TRUE)) + 
scale_x_discrete(limits=c("Taste", "Color of package", "Capacity")) 

只需用參數guides(fill=guide_legend(reverse=TRUE)),手動改變顏色順序和固定與scale_x_discrete X軸的特定順序來實現的。

enter image description here

也可以與DF$Quality <- factor (DF$Quality, levels = c ("Taste", "Color of package", "Capacity"))重新排序的水平,達到同樣的效果,而不使用scale_x_discrete()