Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading