【问题标题】:Need to add legend and fix axis in ggplot [duplicate]需要在ggplot中添加图例和修复轴[重复]
【发布时间】:2021-01-03 20:39:46
【问题描述】:

我是 ggplot 的新手,我正在尝试弄清楚如何将图例添加到图表并重新标记 x 轴。我附上了绘图代码和 resulting graph 。我想添加一个图例来解释蓝线和绿点和红点是什么。我还希望 x 轴上的年份显示为 2018、2019、...、2020,而不是 2017.5、2010.0、...、2020.0。我在在线文档中找不到解决方案。感谢您的帮助。

  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))

【问题讨论】:

    标签: r ggplot2 legend axis-labels


    【解决方案1】:

    使用一些随机示例数据,可以这样实现:

    1. 使用 scale_x_continuous(breaks = scales::pretty_breaks()) 可以提供漂亮的 x 轴中断和标签
    2. 要获得图例,您必须在美学上进行映射,即将color 移动到 aes() 中。然后可以通过scale_color_manual 设置颜色值
    3. 可以通过labs() 设置坐标轴、图例...的标签
    4. 最棘手的部分是让图例正确。为此,我使用guidesguide_legend 来调整图例,以便observed 仅显示一条实线,而对于其他类别仅显示点(形状16)。
    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)
    

    【讨论】:

      猜你喜欢
      • 2016-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-04
      • 2019-01-11
      相关资源
      最近更新 更多