这是我的data.frame()
:
df <- data.frame(Round = rep(c("A", "B", "C" ),150), Group = rep(c("UP", "DOWN"),75),Task = rep(c("T1", "T2", "T3", "T4", "T5"),30), V2 = sample(c(0,1,2), 50, replace = T), V1 = sample(c(0,1,2), 50, replace = T))
dfmelt <- melt(df)
我试图像这样绘制facet_grid
:
b <- ggplot(data=dfmelt, aes(x=value, fill=variable))
b <- b + geom_bar(stat="count", position = "dodge", width = 0.9)
b <- b + facet_grid(Group ~ Task, scales = "free")
,产生以下内容:
我希望摆脱更广泛的列,例如V1 at the position 0 of T1-UP
,V1 at the position 1 of T5-DOWN
和V2 at the position 0 of T3-UP
。
当给定count
位置(0,1或2)中的某个变量(假设为V1)的x
等于0
时,会出现问题其他变量(V2)大于0
。在这种情况下,V2条变宽以填充整个x
位置。
答案 0 :(得分:7)
一种选择是在ggplot
之外手动实施计数,并使用带tidyr::complete
的NA填充缺失的数据,然后执行身份条形图:
library(dplyr); library(tidyr); library(ggplot2)
dfmelt_count <- dfmelt %>%
count(Group, Task, variable, value) %>%
complete(Group, Task, variable, value)
b <- ggplot(data=dfmelt_count, aes(x=value, y = n, fill=variable))
b <- b + geom_bar(stat="identity", position = "dodge", width = 0.9)
b <- b + facet_grid(Group ~ Task, scales = "free")
b