gpt4 book ai didi

r - 如何在一个 ggplot2 图中为两个 geom 图层添加图例?

转载 作者:行者123 更新时间:2023-12-04 12:01:27 24 4
gpt4 key购买 nike

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

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 绘制它,如下所示:
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()

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

enter image description here

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

最佳答案

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

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

plot

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

关于r - 如何在一个 ggplot2 图中为两个 geom 图层添加图例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47023781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com