发生数据丢失时geom_bar的宽度一致

有没有办法在下面的时间序列例子中丢失数据时为geom_bar()设置一个固定的宽度? 我已经尝试在aes()设置width ,但没有运气。 比较2011年5月11日至6月11日在代码示例下方的阴影宽度。

 colours <- c("#FF0000", "#33CC33", "#CCCCCC", "#FFA500", "#000000" ) iris$Month <- rep(seq(from=as.Date("2011-01-01"), to=as.Date("2011-10-01"), by="month"), 15) colours <- c("#FF0000", "#33CC33", "#CCCCCC", "#FFA500", "#000000" ) iris$Month <- rep(seq(from=as.Date("2011-01-01"), to=as.Date("2011-10-01"), by="month"), 15) d<-aggregate(iris$Sepal.Length, by=list(iris$Month, iris$Species), sum) d$quota<-seq(from=2000, to=60000, by=2000) colnames(d) <- c("Month", "Species", "Sepal.Width", "Quota") d$Sepal.Width<-d$Sepal.Width * 1000 g1 <- ggplot(data=d, aes(x=Month, y=Quota, color="Quota")) + geom_line(size=1) g1 + geom_bar(data=d[c(-1:-5),], aes(x=Month, y=Sepal.Width, width=10, group=Species, fill=Species), stat="identity", position="dodge") + scale_fill_manual(values=colours) 

情节

最简单的方法是补充你的数据集,使每个组合都存在,即使它的值是NA 。 举一个简单的例子(因为你有很多不需要的function):

 dat <- data.frame(a=rep(LETTERS[1:3],3), b=rep(letters[1:3],each=3), v=1:9)[-2,] ggplot(dat, aes(x=a, y=v, colour=b)) + geom_bar(aes(fill=b), stat="identity", position="dodge") 

在这里输入图像描述

这显示了你试图避免的行为:在“B”组中,没有组“a”,所以条更宽。 用ab所有组合补充dat帧:

 dat.all <- rbind(dat, cbind(expand.grid(a=levels(dat$a), b=levels(dat$b)), v=NA)) ggplot(dat.all, aes(x=a, y=v, colour=b)) + geom_bar(aes(fill=b), stat="identity", position="dodge") 

在这里输入图像描述

我有同样的问题,但正在寻找一个解决scheme,使用pipe道( %>% )。 从tidyverse使用tidyr::spreadtidyr::gather可以tidyverse一点。 我使用与@Brian Diggs相同的数据,但使用大写variables名时,在变换为宽时不会以双variables名结束:

 library(tidyverse) dat <- data.frame(A = rep(LETTERS[1:3], 3), B = rep(letters[1:3], each = 3), V = 1:9)[-2, ] dat %>% spread(key = B, value = V, fill = NA) %>% # turn data to wide, using fill = NA to generate missing values gather(key = B, value = V, -A) %>% # go back to long, with the missings ggplot(aes(x = A, y = V, fill = B)) + geom_col(position = position_dodge())