How to add a legend label in a plot, when there is no data points with that label in the specific plot?

StackOverflow https://stackoverflow.com/questions/22276761

  •  11-06-2023
  •  | 
  •  

Question

I've made a GIF of a series of plots (scatterplots), which display points of latitude and longitude from year to year showing species distribution and population distribution. However, in some years, there are no values for some species (ie. no individuals were collected in that year). This creates a problem in a GIF, because the legends should be constant from plot to plot.

I want to be able to manually include or insert these missing species in the legend, with the species names and colour values accordingly (even if they are not in the plot shown).

Reproducible example (although I don't know if it's necessary):

    #Creating mock longitude and latitude poitns
    a <- c("1","1")
    b <- c("2","2")
    c <- c("3","1")
    d <- c("2","1")
    e <- c("2","3")
    f <- c("3","3")

    x <- rbind(a,b,c,d,e,f)
    #Assigning species to each observation.
    sp <- c("sp1", "sp1", "sp1", "sp1", "sp1", "sp2")
    year <- c(2000, 2000, 2000, 1999, 1999, 1999)

    x2 <- cbind(x, sp, year)

    df <- as.data.frame(x2)
    #Subset the df by year, which I have to do in my original dataset. 
    df99 <- subset(df, year==1999)
    df00 <- subset(df, year==2000)

    g1999 <- ggplot(data=df99, aes(V1, V2, colour=sp)) + geom_point()
    g2000 <- ggplot(data=df00, aes(V1, V2, colour=sp)) + geom_point()

In this case, I would like to show on the plot legend, the label and colour for both Sp1 and Sp2.

Any help is greatly appreciated!

Was it helpful?

Solution

The first alternative is to add a geom_blank as a first layer in the plot call. From ?geom_blank: "The blank geom draws nothing, but can be a useful way of ensuring common scales between different plots.". Here we let the geom_blank layer use the entire data set, df. Thus, even though only a subset of the data is used for the actual plotting made by geom_point, a legend with all species is created.

ggplot(data = df, aes(V1, V2, colour = sp)) +
  geom_blank() +
  geom_point(data = df99)

enter image description here

ggplot(data = df, aes(V1, V2, colour = sp)) +
  geom_blank() +
  geom_point(data = df00)

enter image description here

Another possibility is to use facet_wrap, which puts the plots for each year together with one common scale.

ggplot(data = df, aes(V1, V2, colour = sp)) +
  geom_point() +
  facet_wrap(~ year)

enter image description here

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top