How to add a traditional legend to dumbbell plot created using ggalt::geom_dumbbell
in R
?
This question has an answer with an in-chart legend. How to map the aesthetics to get a separate legend for the points on the side/bottom ?
library(ggalt)
df <- data.frame(trt=LETTERS[1:5], l=c(20, 40, 10, 30, 50), r=c(70, 50, 30, 60, 80))
ggplot(df, aes(y=trt, x=l, xend=r)) +
geom_dumbbell(size=3, color="#e3e2e1",
colour_x = "red", colour_xend = "blue",
dot_guide=TRUE, dot_guide_size=0.25) +
theme_bw()
One way to get a legend is to add a points layer based on the dataset in long format, mapping
color
to the grouping variable.First, make a long format dataset via
gather
from tidyr.Then make the plot, adding the new points layer with the long dataset and using
scale_color_manual
to set colors. I moved thegeom_dumbbell
specific aesthetics into that layer.