I'm trying to obtain a plot like the one shown in Combined bar plot and points in ggplot2, with the points off to the side of the bars. One of the answers suggests to subtract an offset from the x values in geom_point()
, and that works; but my problem comes when x values are not numbers since I can't subtract a number to them.
For example, this works:
df = data.frame(Xval = c(2, 4, 6), Yval = c(5, 6.1, 5.4))
ggplot()
geom_bar(df, mapping = aes(Xval, Yval), stat = "identity", width = 0.5, color = "black", fill = "#92DAB8")
geom_point(df, mapping = aes(Xval-.5, Yval))
But this does not work:
df2 = data.frame(Xval = c("A", "B", "C"), Yval = c(5, 6.1, 5.4))
ggplot()
geom_bar(df2, mapping = aes(Xval, Yval), stat = "identity", width = 0.5, color = "black", fill = "#92DAB8")
geom_point(df2, mapping = aes(Xval-.5, Yval))
Is there any way to do the offset like in the first plot? Ideally, I would like to have a solution that works in both cases since I want to make a "plotter" function and you wouldn't know beforehand whether the values of X are numbers, but any solution (even one that implies doing the trick in two different ways depending on the X values) will be helpful. Maybe there is a way to get the actual X values in the plot, but I searched for solutions following this idea and found nothing. Thanks in advance!
CodePudding user response:
In your case one option would be to use position_nudge
to shift the points:
plot_fun <- function(.data, nudge_x = 0) {
ggplot(.data)
geom_bar(aes(Xval, Yval), stat = "identity", width = 0.5, color = "black", fill = "#92DAB8")
geom_point(aes(Xval, Yval), position = position_nudge(x = nudge_x))
}
library(ggplot2)
df = data.frame(Xval = c(2, 4, 6), Yval = c(5, 6.1, 5.4))
df2 = data.frame(Xval = c("A", "B", "C"), Yval = c(5, 6.1, 5.4))
plot_fun(df, nudge_x = -.5)
plot_fun(df2, nudge_x = -.5)