fawda123 / ggord

a take on ordination plots using ggplot2
https://fawda123.github.io/ggord/
62 stars 20 forks source link

legend for species points #12

Closed iembry closed 6 years ago

iembry commented 6 years ago

Hi, is there already a way to add a legend for the species points?

Thank you.

fawda123 commented 6 years ago

This is tricky to do within the function because the point geometries for the sites and species are separate. Here's a workaround that might help, basically just stitching a made up legend to the existing ggord plot:

library(vegan)
library(gridExtra)
library(ggplot2)
library(ggord)

# function to extract legend
g_legend <- function(a.gplot){
  tmp <- ggplot_gtable(ggplot_build(a.gplot))
  leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
  legend <- tmp$grobs[[leg]]
  return(legend)}

# made up legend data
legdata <- data.frame(
  x = c(1, 2), 
  y = c(1, 2), 
  group = c('Site', 'Species')
)

# legend plot
pleg <- ggplot(legdata, aes(x = x, y = y, colour = group, size = group)) +
  geom_point() + 
  scale_size_manual(values = c(4, 2)) +
  scale_colour_manual(values = c('black', 'blue')) +
  theme_bw() +
  theme(legend.title = element_blank())

# extract legend from plot
pleg <- g_legend(pleg)

# actual data and ordination triplot
data(varespec)
data(varechem)
ord <- rda(varespec, varechem)

p <- ggord(ord)

# combine the two with gridExtra
grid.arrange(p, pleg, ncol = 2, widths = c(1, 0.2))

image