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")
這個問題是關係到過去類似的問題(例如,Don't drop zero count),但所提出的解決方案不能在這裏工作。
預先計算的值不工作?聽起來像是一個挑戰。 :) –
我正在尋找更多的編程解決方案。 – Andrej
哎呀,忘了計算相對頻率。查看我的(新)編輯。 –