2017-10-04 154 views
0

我有一個數據集,其中單個樣本屬於一個大組和一個較小的子組。每個組有幾個子組,但每個子組只能屬於一個較大的組。同樣,每個樣本只能屬於一個小組,因此屬於一個較大的小組。使用ggplot堆積條形圖中的多個色階

我希望做一個真/假堆疊條形圖兩種顏色的含義:

  • 綱要(顏色)是大組
  • 填充是真/假數據,但 是兩種色調的較大的組輪廓顏色。

這是接近我想要的,但不是淺灰色和深灰色,我喜歡紅色水果的明亮和深紅色,綠色水果的明亮和深綠色以及淺綠色和深藍色藍色水果。

fruit <- data.frame(Sample=1:20, 
       Fruit=c(rep("Apple", 3), rep("Strawberry", 2), rep("Grape", 4), 
         rep("Watermelon", 4), rep("Lime", 3), rep("Blueberry", 2), 
         rep("Plum", 2)), 
       Color=c(rep("Red", 9), rep("Green", 7), 
         rep("Blue", 4)), 
       Ripe=c(rep(c(T, F), 10))) 

fruit$Fruit <- factor(fruit$Fruit, unique(fruit$Fruit)) 
fruit$Color <- factor(fruit$Color, unique(fruit$Color)) 

ggplot(fruit, aes(Fruit)) + 
    theme_bw() + 
    geom_bar(stat="count", position="fill", 
      aes(fill=Ripe, color=Color)) + 
    scale_fill_manual(values=c("grey65", "grey85")) + 
    scale_y_continuous(labels=scales::percent) 

example

這可能嗎?還是有更好的方法,我可以直觀地將較大羣體成員與真/假值區分開來嗎? 感謝

+0

使用alpha審美:https://stackoverflow.com/a/33222028/471093 – baptiste

回答

3

編輯:這可能是做了,用interaction分配獨特的顏色各因素對的比較正確的做法:

ggplot(fruit, aes(Fruit)) + 
    geom_bar(aes(fill=interaction(Color,Ripe), color=Color), stat="count", position="fill")+ 
    scale_y_continuous(labels=scales::percent)+ 
    scale_fill_manual(values=c("pink","lightgreen","lightblue","red", "green","blue"))+ 
    theme_bw() 

enter image description here

地圖顏色到fill,和成熟爲alpha

ggplot(fruit, aes(Fruit)) + 
    geom_bar(stat="count", position="fill", 
      aes(fill=Color, color=Color,alpha=Ripe)) + 
    scale_y_continuous(labels=scales::percent)+ 
    scale_alpha_discrete(range=c(.5,1))+ 
    theme_bw() 

enter image description here

+0

謝謝!我更喜歡使用alpha的外觀。 – hmg

+0

在第二個例子中,如果我想要y軸是「計數」水果而不是百分比,會怎樣?另外,成熟爲「計數」... – guidebortoli

+1

@guidebortoli我會用'dplyr'首先彙總:'fruit2 <- fruit %>%group_by(Fruit,Ripe)%>%summarize(count = n(),Color = first(Color ))'then'ggplot(fruit2,aes(Fruit,count))+ geom_bar(stat =「identity」,aes(fill = interaction(Color,Ripe),color = Color))+ scale_fill_manual(values = c(「pink 「,」lightgreen「,」lightblue「,」red「,」green「,」blue「))+ theme_bw()' – Mako212