如何在一个 ggplot2 图中为两个 geom 图层添加图例? [英] How to add a legend for two geom layers in one ggplot2 plot?

查看:59
本文介绍了如何在一个 ggplot2 图中为两个 geom 图层添加图例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的数据框:

I've got a data frame that looks like this:

glimpse(spottingIntensityByMonth)
# Observations: 27
# Variables: 3
# $ yearMonth <dttm> 2015-05-01, 2015-06-01, 2015-07-01, 2015-08-01, 2015-09-01, 2015-10-01, 2...
# $ nClassificationsPerDayPerSpotter <dbl> 3.322581, 13.212500, 13.621701,
    6.194700, 18.127778, 12.539589, 8.659722, ...
# $ nSpotters <int> 8, 8, 22, 28, 24, 22, 24, 27, 25, 29, 32, 32, 21, 14, 18, 13, 20, 19, 15, ...

我正在尝试使用 ggplot2 绘制它,如下所示:

I am trying to plot it with ggplot2 like so:

ggplot() + 
    geom_col(data = spottingIntensityByMonth, 
             mapping = aes(x = yearMonth, 
                           y = nClassificationsPerDayPerSpotter)
             ) + 
    xlab("Month of year") + 
    scale_y_continuous(name = "Daily classifications per Spotter") + 
    geom_line(data = spottingIntensityByMonth, 
              mapping = aes(x = yearMonth,
                            y = nSpotters)
              ) +
    theme_bw()

这会产生一个像这样的情节:

This produces a plot like so:

现在我想添加一个说明行和列的含义的图例.我该怎么做呢?谢谢!

Now I want to add a legend that says what the line and columns mean. How do I do this? Thanks!

推荐答案

在 ggplot 中,会自动为映射美学创建图例.您可以按如下方式添加此类映射:

In ggplot, legends are automatically created for mapped aesthetics. You can add such mappings as follows:

ggplot(data = df, 
       mapping = aes(x = x)) + 

  # specify fill for bar / color for line inside aes(); you can use
  # whatever label you wish to appear in the legend
  geom_col(aes(y = y.bar, fill = "bar.label")) +
  geom_line(aes(y = y.line, color = "line.label")) +

  xlab("Month of year") + 
  scale_y_continuous(name = "Daily classifications per Spotter") + 

  # the labels must match what you specified above
  scale_fill_manual(name = "", values = c("bar.label" = "grey")) +
  scale_color_manual(name = "", values = c("line.label" = "black")) +

  theme_bw()

在上面的例子中,我还移动了数据 &常见的美学映射 (x) 到 ggplot().

In the above example, I've also moved the data & common aesthetic mapping (x) to ggplot().

样本数据集:

set.seed(7)
df <- data.frame(
  x = 1:20,
  y.bar = rpois(20, lambda = 5),
  y.line = rpois(20, lambda = 10)
)

这篇关于如何在一个 ggplot2 图中为两个 geom 图层添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆