问题
I'm new to ggplot and I'm trying to figure out how to add a legend to a graph and re-label the x-axis. I've enclosed the plotting code and resulting graph . I would like to add a legend that explains what the blue line and the green and red dots are. I would also like the years on the x-axis to appear as 2018, 2019, ... , 2020 instead of 2017.5, 2010.0, ..., 2020.0. I can't find a solution in the online documentation. Thanks for your help.
ggplot(data = annual_rate_preds) +
geom_point(mapping = aes(x = year, y = predicted), color = 'green') +
geom_line(mapping = aes(x = year, y = observed), color = 'blue') +
geom_point(data = backfit_rate_preds, mapping = aes(x = target_year, y = rate_pred),
shape = 18, color = 'red', size = 2) +
theme(plot.title = element_text(size = 10))
回答1:
Using some random example data this could be achieved like so:
- Using
scale_x_continuous(breaks = scales::pretty_breaks())
gives pretty x-axis breaks and labels - To get a legend you have to map on aesthetics, i.e. move
color
inside aes(). The color values can then be set viascale_color_manual
- Labels for the axes, legend, ... can be set via
labs()
- Most tricky part is to get the legend right. To this end I make use of
guides
andguide_legend
to adjust the legend such that forobserved
only a solid line is shown while for the other categories only points (shape 16) show up.
library(ggplot2)
set.seed(42)
annual_rate_preds <- data.frame(
predicted = runif(13, -.1, .1),
observed = runif(13, -.1, .1),
year = 2008:2020
)
backfit_rate_preds<- data.frame(
rate_pred = runif(13, -.1, .1),
target_year = 2008:2020
)
ggplot(data = annual_rate_preds) +
geom_point(mapping = aes(x = year, y = predicted, color = 'predicted')) +
geom_line(mapping = aes(x = year, y = observed, color = 'observed')) +
geom_point(data = backfit_rate_preds, mapping = aes(x = target_year, y = rate_pred, color = 'rate_pred'),
shape = 18, size = 2) +
scale_x_continuous(breaks = scales::pretty_breaks()) +
scale_color_manual(values = c(predicted = "green", observed = "blue", rate_pred = "red")) +
theme(plot.title = element_text(size = 10)) +
guides(color = guide_legend(override.aes = list(linetype = c("solid", "blank", "blank"), shape = c(NA, 16, 16)))) +
labs(x = "Year", y = NULL, color = NULL)
来源:https://stackoverflow.com/questions/65554701/need-to-add-legend-and-fix-axis-in-ggplot