这是我的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
给定x
位置(0,1或2)中的一个变量(假设为V1)等于0
且另一个变量(V2)大于时,会出现问题0
.在这种情况下,V2条变宽以填充整个x
位置.
我曾尝试这个和这个解决方案没有成功.有没有办法让条形有一个固定的宽度?
一种选择是在外面手动实现计数ggplot
,并使用NA填充缺失数据,tidyr::complete
然后执行标识栏图:
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