在图例中分隔 geom_point 和 geom_line

separating geom_point and geom_line in legend

我有一个列和点叠加的数据集。绘图相当简单,但我似乎无法让 geom_point 作为单独的图例出现。相反,它默认将两者结合起来。

我试过将点添加为单独的数据框,将映射点添加为因子,以及在论坛上找到的无穷无尽的函数。有什么提示吗?

下面的简化示例:

library(ggplot2)
Site <- c("A", "B", "C", "A", "B", "C")
Year <- c(2020, 2020, 2020, 2019, 2019, 2019)
Geomean <- c(65,184,27,21,67,51)
Historical.Geomean <- c(76,81,44,76,81,44)

df <- data.frame(Site, Year, Geomean, Historical.Geomean)

df$Year <- as.factor(df$Year)

fw_ecoli_plot <-
  ggplot(df) +
  geom_col(aes(x=Site, y=Geomean, fill=Year), position="dodge") +
  geom_point(aes(x=Site, y=Historical.Geomean),
             color="black", pch=18, show.legend = T) +
  theme_bw()

fw_ecoli_plot

这个怎么样:

Site <- c("A", "B", "C", "A", "B", "C")
Year <- c(2020, 2020, 2020, 2019, 2019, 2019)
Geomean <- c(65,184,27,21,67,51)
Historical.Geomean <- c(76,81,44,76,81,44)

df <- data.frame(Site, Year, Geomean, Historical.Geomean)

df$Year <- as.factor(df$Year)

fw_ecoli_plot <-
    ggplot(df) +
    geom_col(aes(x=Site, y=Geomean, fill=Year), position="dodge" ) +
    geom_point(aes(x=Site, y=Historical.Geomean, colour="Historical Mean"),
               pch=18) +
    scale_colour_manual(values="black") + 
    labs(colour="") + 
    theme_bw()

fw_ecoli_plot

通过将值放入 aes,您基本上是在生成一个新的因子变量和一个图例。

如果您将值放在 aes 之外 -> ggplot 将不会创建图例。你可以试试看:

  df %>% 
    ggplot(aes(x=Site, y=Geomean))+
    geom_col(aes(fill=Year), position="dodge") +
    geom_point(aes(x=Site, y=Historical.Geomean, color="black"), pch=18, show.legend = T) +
    scale_color_manual(values = c('black' = 'black'))+
    guides(fill = guide_legend(override.aes = list(shape = NA)))+
    theme_bw()