Plotting counts using ggplot2's geom_bar(stat="identity")
is an effective method of visualising counts. I would like to use this method to display my observed counts and compare them to expected counts I would like to do this by using geom_step
to overlay a stairstep plot layer over the barplot.
However when I do this I run into the problem that barplots by default have their positions dodged but geom_step
does not. For example using both continuous and discrete dependent variables:
library(tidyverse)
test <- data_frame(a = 1:10, b = runif(10, 1, 10))
test_plot <- ggplot(test, aes(a, b)) +
geom_bar(stat="identity") +
geom_step(color = 'red')
test2 <- data_frame(a = letters[1:10], b = runif(10, 1, 10))
test2_plot <- ggplot(test2, aes(a, b, group = 1)) +
geom_bar(stat="identity") +
geom_step(color = 'red'))
gridExtra::grid.arrange(test_plot, test2_plot, ncol = 2)
As you can see the two layers are offset which is undesirable.
Reading the docs I see that geom_path
has a position =
option however trying something like geom_step(color = 'red', position = position_dodge(width = 0.5))
does not do what I want rather it compresses the bars and the stairstep line towards the centre. Another option is to adjust the data directly like this geom_step(aes(a-0.5, b), color = 'red')
which produces a near acceptable result for data with continuous dependent variables. You could also calculate the stairstep line as a function and plot it using stat_function()
.
However these approaches are not applicable to data with discrete dependent variables and my actual data has discrete dependent variables so I need another answer.
Additionally when shifted the stairstep line will not cover the last bar as seen in the above image. Is there an easy elegant way to extend it to cover the last bar?
If geom_step()
is the wrong approach and what I'm trying to get can be achieved in another way I am interested in that too.