I’ve put together this graph and I would like to be able to add a legend to it but can’t seem to figure out why it’s not showing up and how to easily add it.
data <- data.frame(group = LETTERS[1:5], # Create example data
pol_nb = c(1000, 800, 1200, 900, 800),
Prediction = c(0.6, 0.9, 0.9, 0.5, 0.8),
Actual = c(0.5, 1.0, 1.2, 1.5, 0.9))
buffer <- 0.5
scale <- max(data$Prediction)/max(data$pol_nb)
total <- sum(data$pol_nb)
ggplot(data) +
### add model fitted prediction
geom_point(aes(x = group, y = Prediction), group = 1, shape = 21, size = 3, color = "black", fill = "green3") +
geom_line(aes(x = group, y = Prediction), group = 1, color = "green3") +
### add actual average
geom_point(aes(x = group, y = Actual), group = 1, shape = 22, size = 3, color = "black", fill = "purple") +
geom_line(aes(x = group, y = Actual), group = 1, color = "purple") +
### add bars
geom_col(aes(x = group, y = pol_nb * buffer * scale), color = "black", fill = "gold", width = 0.5) +
scale_y_continuous(
name = "Prediction",
sec.axis = sec_axis(~ ./ (buffer * scale * total),
name = 'PoliciesDistribution',
labels = scales::label_percent())) +
theme_light()
I’ve figured out from this threadif you put the color inside of the aes() that it does appear but not in the way I would expect.
New contributor
Patrick Jung is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.