Is there a way to set a constant width for geom_bar()
in the event of missing data in the time series example below? I've tried setting width
in aes()
with no luck. Compare May '11 to June '11 width of bars in the plot below the code example.
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)
geom_bar() makes the height of the bar proportional to the number of cases in each group (or if the weight aesthetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use geom_col() instead.
In geom_bar() , the default dependent measure is the count (i.e., stat = "count" by default). In the above example, we've overridden the default count value by specifying stat = "identity" . This indicates that R should use the y-value given in the ggplot() function.
position_dodge.Rd. Dodging preserves the vertical position of an geom while adjusting the horizontal position.
When we want to Increase the Width of Bars and Decrease Space between Bars, we simply have to use width parameter to the geom_bar() function. Here we set the value of the width parameter as 0.98. You can choose the value of 'width' parameter between 0.00 to 1.00 as per your requirements.
Some new options for position_dodge()
and the new position_dodge2()
, introduced in ggplot2 3.0.0 can help.
You can use preserve = "single"
in position_dodge()
to base the widths off a single element, so the widths of all bars will be the same.
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)
Using position_dodge2()
changes the way things are centered, centering each set of bars at each x axis location. It has some padding
built in, so use padding = 0
to remove.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With