2017-08-03 54 views
0

我試圖繪製一個簡單的條形圖。我想保留空閒空間用於未使用的級別。但是,drop=FALSE處的scale_fill_manualscale_x_discrete不能像預期的那樣工作。第一個網格工作,但不是第二個,也不知道爲什麼。無論我把drop = FALSE放在scale_x_discrete,scale_fill_manual或兩者都有,結果都一樣。ggplot2 drop = FALSE與facet_grid不一致

我的數據使用reshape2包進行融化。

> head(wd_long) 
    tenure weight_all age_group variable value 
463 Owned 908.7858   1 partner Yes 
477 Owned 908.7858   2 partner Yes 
478 Owned 908.7858   1 partner Yes 
482 Owned 908.7858   1 partner Yes 
483 Owned 908.7858   1 partner Yes 
496 Rented 1043.1573  1 partner Yes 

和情節:

ggplot(wd_long, aes(x= variable, group = age_group)) + 
    geom_bar(aes(y = ..prop.., fill = age_group, weight = weight_all), 
     width = 0.7, stat = "count", position = position_dodge(width = 0.8)) + 
    geom_text(aes(label = scales::percent(..prop..), y = ..prop.. , weight = weight_all), 
      position = position_dodge(width = 0.8), stat = "count", vjust = -1, size = 3) + 
    scale_fill_manual(values = c("#004F66", "#BFE391"), labels = c("65-74\nyears old ", "Over 75\nyears old"), drop = FALSE) + 
    scale_x_discrete(drop = FALSE) + 
    scale_y_continuous(limits = c(0, 0.75), breaks = c(0, 0.25, 0.5, 0.75), labels = c(0, "", 50, "")) + 
    labs(x = "Living Arrangement", y = "", fill = "") + 
    theme(strip.text = element_text(size = 9, face = "bold"), 
     axis.title = element_text(size = 9), axis.text = element_text(size = 8), 
     legend.position = "bottom", legend.text = element_text(size = 8)) + 
    facet_grid(tenure ~ .) 

enter image description here

請幫幫忙!我不明白爲什麼會發生這種情況......

+0

請張貼再現的問題(如「不相關」和「獨」類別)的最小數據集 – tonytonov

+0

另見https://stackoverflow.com/questions/17888456/why-this-小格 - 犯規 - 刪除 - 列/ 17888571#17888571 – tonytonov

回答

0

我解決了我自己的問題,但它只是一個小小的作弊,因爲我在我的數據中使用了權重。我爲一個未使用的元素添加了一條虛擬線,「已租用,與之無關,65-74歲」,並賦予其零權重。

它解決了表面上的問題,但我相信它不是真正的答案... 雖然現在這樣做!

enter image description here

相關問題