2016-02-05 65 views
0

我有數據集具有三個分類變量堆積條形圖具有三個分類和一個numrical列

data_input <- structure(list(Var1 = structure(c(4L, 4L, 3L, 5L, 6L, 7L, 3L, 
5L, 6L, 7L, 3L, 4L, 5L, 6L, 7L, 3L, 4L, 5L, 6L, 7L), 
.Label = c("CHEER","CHOIR", "DEEP", "OVER", "PEER", "PEEN", "POST"), 
class = "factor"), 
Var2 = c("Good", "Bad", "Good", "Good", 
"Good", "Good", "Bad", "Bad", 
"Bad", "Bad", "Good", "Good", 
"Good", "Good", "Good", "Bad", 
"Bad", "Bad", "Bad", "Bad"), 
Type = c("New", 
"New", "New", "New", "New", "New", "New", "New", "New", "New", 
"Old", "Old", "Old", "Old", "Old", "Old", "Old", "Old", "Old", 
"Old"), value = c(0, 0, 4, 28, 4, 7, 8, 10, 3, 2, 36, 10, 
23, 31, 7, 19, 3, 14, 12, 4)), 
.Names = c("Var1", "Var2", "Type", "value"), 
row.names = c(NA, -20L), class = "data.frame") 

我用下面的代碼以產生所述情節

ggplot(data = data_input, aes(x = reorder(Var1, Var2), y = value)) + 
geom_bar(stat = "identity", position = "stack", aes(fill = Var2)) + 
labs(y = "\n Total Number of Counts", x = NULL) 

它產生像enter image description here

的曲線圖

但是,它不直觀地區分不同類型。我們可以爲不同類型或不同類型的顏色區分它們以及圖例。

+0

你什麼意思,'沒有不同類型之間的視覺區分:;數據分離成單獨的面板,在這裏使用類型變量(右OldNew子在左邊) '?它顯示了'Var2'中的兩個級別?你想顯示不同的變量? – ako

回答

3

可能有兩種解決方案。首先,根據Type更改條形的顏色。

ggplot(data = data_input, aes(x = reorder(Var1, Var2), y = value)) + 
     geom_bar(stat = "identity", position = "stack", aes(fill = Var2,color=Type),size=1) + 
     scale_color_manual(values=c("black","grey75"))+ 
     labs(y = "\n Total Number of Counts", x = NULL) 

enter image description here

二,使用TypeVar 2之間的相互作用用於填充。

ggplot(data = data_input, aes(x = reorder(Var1, Var2), y = value)) + 
     geom_bar(stat = "identity", position = "stack", aes(fill = interaction(Type,Var2))) + 
     labs(y = "\n Total Number of Counts", x = NULL) 

enter image description here

4

雖然你的問題是不完全清楚我的,你不使用你的情節在所有變量type,所以這是一兩件事改變。

現在,當你有了你的尺寸,你可能想要面對它;

ggplot(data = data_input, aes(x = Var1, y = value)) + 
    geom_bar(stat = "identity", position = "stack", aes(fill = Var2)) + 
    facet_wrap(~Type)+ 
    labs(y = "\n Total Number of Counts", x = NULL) 

enter image description here