2017-05-29 79 views
1

假設我們有以下的玩具數據結構:迴避barplot與零個計數GGPLOT2

data <- structure(list(value = c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 
2L, 2L, 2L, 3L, 3L, 3L, 3L), class = structure(c(1L, 1L, 1L, 
2L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L), .Label = c("A", 
"B"), class = "factor")), .Names = c("value", "class"), class = "data.frame", row.names = c(NA, 
-16L)) 

在這個數據的一個分組具有零計數(即,存在用於B類與值沒有計數3):

> library(dplyr) 
> count(data, value, class) 
Source: local data frame [5 x 3] 
Groups: value [?] 

    value class  n 
    <int> <fctr> <int> 
1  1  A  3 
2  1  B  3 
3  2  A  4 
4  2  B  2 
5  3  A  4 

下面的代碼繪製了barplot(相對頻率在y軸上),但我需要顯示零計數的空白空間。相反,ggplot2消除零計數的條形。任何建議如何包括零計數?

ggplot(data, aes(value, fill = class)) + 
geom_bar(aes(y = ..count../sapply(fill, FUN=function(x) sum(count[fill == x]))), position="dodge") 

enter image description here

這個問題是關係到過去類似的問題(例如,Don't drop zero count),但所提出的解決方案不能在這裏工作。

+0

預先計算的值不工作?聽起來像是一個挑戰。 :) –

+0

我正在尋找更多的編程解決方案。 – Andrej

+1

哎呀,忘了計算相對頻率。查看我的(新)編輯。 –

回答

2

這個程序化不夠嗎?我預先計算一切並繪製它...注意table對於沒有數據的因子組合「計數」爲零。

library(ggplot2) 
xy <- table(data$class, data$value) 
xy <- as.data.frame(xy) 

xy$rel.freq <- xy$Freq/aggregate(Freq ~ Var1, FUN = sum, data = xy)$Freq 

ggplot(xy, aes(x = Var2, y = rel.freq, fill = Var1)) + 
    theme_bw() + 
    scale_fill_brewer(palette = "Set1") + 
    geom_bar(stat = "identity", position = "dodge") 

enter image description here