I'm trying to make a dumbbell chart with additional information about change (green/red) and significance of the change (vol) and add an additional legend for the dots at the end of the dumbbells.
My code to generate below plot is:
library(ggalt)
# build data set
set.seed(1)
df <- data.frame(country=paste("Region", LETTERS[1:10]))
df$last_year <- runif(nrow(df))
df$this_year <- runif(nrow(df))
df$ydiff <- df$this_year - df$last_year
df$vol <- runif(nrow(df))
# create dumbbell plot
ggplot(df, aes(y=country, group=country)) +
geom_dumbbell(aes(x=last_year, xend=this_year, colour = ydiff, size=vol),
colour_x = "blue",
colour_xend = "yellow") +
scale_color_gradient2(low="green", high="red")
Now, I'd like to add a legend about what the yellow and blue dots are. I tried to follow the approach in this answer, but it did not work:
# Use answer with long data
df2 <- melt(df[, c("country", "last_year", "this_year")])
# create point alone works
ggplot() + geom_point(data=df2, aes(x=value, y=country, color=variable))
# create dumbbell alone works
ggplot() + geom_dumbbell(data=df, mapping=aes(x=last_year, xend=this_year, y=country, colour = ydiff, size=vol))
# combining plots does not work
ggplot() + geom_point(data=df2, aes(x=value, y=country, color=variable)) +
geom_dumbbell(data=df, mapping=aes(x=last_year, xend=this_year, y=country, colour = ydiff, size=vol))
# Error: Continuous value supplied to discrete scale
I don't know how to access the aesthetics in the dumbbell chart and plot a legend automatically either. Can you point me to a solution?