在count = 0的情况下,如何使用geom_bar()去掉ggplot2图的较宽条

时间:2017-01-16 23:56:25

标签: r ggplot2 geom-bar

这是我的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")

,产生以下内容:

enter image description here

我希望摆脱更广泛的列,例如V1 at the position 0 of T1-UPV1 at the position 1 of T5-DOWNV2 at the position 0 of T3-UP

当给定count位置(0,1或2)中的某个变量(假设为V1)的x等于0时,会出现问题其他变量(V2)大于0。在这种情况下,V2条变宽以填充整个x位置。

我尝试过此thisthis解决方案但没有成功。 有没有办法让条形有一个固定的宽度?

1 个答案:

答案 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

enter image description here