1

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

user438383
  • 5,716
  • 8
  • 28
  • 43

2 Answers2

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

DaveArmstrong
  • 18,377
  • 2
  • 13
  • 25
0

By putting the values in aes, you're basically generating a new factor variable and a legend.

If you put the the values outside of aes -> ggplot won't create a legend. You can try it out:

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

enter image description here

TarJae
  • 72,363
  • 6
  • 19
  • 66