Need to add legend and fix axis in ggplot [duplicate]

六月ゝ 毕业季﹏ 提交于 2021-01-29 17:22:04

问题


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:

  1. Using scale_x_continuous(breaks = scales::pretty_breaks()) gives pretty x-axis breaks and labels
  2. To get a legend you have to map on aesthetics, i.e. move color inside aes(). The color values can then be set via scale_color_manual
  3. Labels for the axes, legend, ... can be set via labs()
  4. Most tricky part is to get the legend right. To this end I make use of guides and guide_legend to adjust the legend such that for observed 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!