'separating geom_point and geom_line in legend

I have a dataset with columns and points superimposed. The plotting is fairly simple but I can't seem to get geom_point to appear as a separate legend. Instead it defaults to combining the two.

I have tried adding the points as separate dataframe, mapping points as factors, and endless functions found on forums. Any hints?

Simplified example below:

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

Resulting plot



Solution 1:[1]

How about this:

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

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1