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!
Specify Labels Using DisplayName Alternatively, you can specify the legend labels using the DisplayName property. Set the DisplayName property as a name-value pair when calling the plotting functions. Then, call the legend command to create the legend. Legends automatically update when you add or delete a data series.
A legend is a key to a plot that labels data by color, pattern, and symbol. This example shows a basic legend. displaying two plots on one graph.
By default, seaborn automatically adds a legend to the graph. Notice the legend is at the top right corner. If we want to explicitly add a legend, we can use the legend() function from the matplotlib library. In this way, we can add our own labels explicitly.
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)
ggplot(data = df, aes(V1, V2, colour = sp)) +
geom_blank() +
geom_point(data = df00)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With