有没有一种方法来设置一个固定的宽度geom_bar()
在下面的时间序列例如丢失数据的情况下? 我试过设置width
在aes()
没有运气。 在下面的代码示例情节五月'11相较于六月'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)
Answer 1:
最简单的方法是补充你的数据集,使每一个组合的存在,即使它有NA
作为其值。 以一个简单的例子(如你有很多不必要的功能):
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”组的,所以酒吧更宽。 补充dat
用的所有组合一个数据帧a
和b
:
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")
Answer 2:
我有同样的问题,但一直在寻找与管(有效的解决方案%>%
使用tidyr::spread
和tidyr::gather
从tidyverse
的伎俩。 我用的是相同的数据@布赖恩·迪格斯,但大写的变量名不与转化到宽时,双变量名结束:
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())
编辑:
这里实际上是一个更简单的解决这一问题,结合管道。 使用tidyr::complete
给出一个线相同的结果:
dat %>%
complete(A, B) %>%
ggplot(aes(x = A, y = V, fill = B)) +
geom_col(position = position_dodge())
Answer 3:
对于一些新的选项position_dodge()
和新position_dodge2()
在GGPLOT2 3.0.0介绍可以提供帮助。
可以使用preserve = "single"
中position_dodge()
至基部的宽度过单独的元件,因此,所有条的宽度将是相同的。
ggplot(data = d, aes(x = Month, y = Quota, color = "Quota")) +
geom_line(size = 1) +
geom_col(data = d[c(-1:-5),], aes(y = Sepal.Width, fill = Species),
position = position_dodge(preserve = "single") ) +
scale_fill_manual(values = colours)
使用position_dodge2()
改变事物居中的方式,围绕每一组在每个x轴位置栏。 它有一些padding
内置的,所以用padding = 0
清除。
ggplot(data = d, aes(x = Month, y = Quota, color = "Quota")) +
geom_line(size = 1) +
geom_col(data = d[c(-1:-5),], aes(y = Sepal.Width, fill = Species),
position = position_dodge2(preserve = "single", padding = 0) ) +
scale_fill_manual(values = colours)
文章来源: Consistent width for geom_bar in the event of missing data