本文介绍了如何在一个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图层添加图例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 19:10