Plotting smooth surfaces on NMDS plots with ggplot
The RMarkdown source to this file can be found here
A little while back I showed how to produce NMDS plots using the vegan and ggplot2 packages. In this post, I will extend the production of the NMDS plots to reproducing the smooth surface plots produced by the function ordisurf in the vegan package.
From the documentation, ordisurf, which requires package mgcv) fits smooth surfaces for continuous variables onto ordination using thinplate splines with cross-validatory selection of smoothness.
Similar to reasons I mentioned when making NMDs plots in my previous posts, these plots look a whole lot better and easier to make publication ready using ggplots themes
ordisurf plots using base plots
Load the required libraries. For this demonstration I will use the dune dataset within the vegan package. The analysis I am showing here is based on information presented in the Vegan: an introduction to ordinationvignette by Jari Oksanen
Run the ordination on the dune dataset and plot the result with base graphics
Now fit continuous environmental factors from the dune.env dataset using ordisurf.
ordisurf plots using ggplot
The first step is to extract the data from the ord object and put it into a dataframe. For the purpose of this demonstration, I am going to just focus on the species scores.
Notice that I add a ‘z’ column filled with NAs, which allows the score data sets to be combined with the contour dataset.
Next step is to run the ordisurf function as above.
We need to extract the contour information from dune.sf object. This is in the $grid. I wrote a function that will pull out this information and put it into a dataframe with the column headers ‘x’, ‘y’, and ‘z’.
We now have the required information to reproduce the plot from ordisurf in ggplot2. The first step is the lay down the contours in the plot.
Then add the species scores. Note that I am using theme_mine which can be sourced from my themes.r file
Adding contour labels
The trickiest part of reproducing the contours is getting the contour labels on the lines. I usually manually create a data.frame and manually set the points that I want the labels.
The other option is to take advantage of the directlabels package and utilize the function direct.labels().
As I have demonstrated that the key to using ggplot2 to produce plots is to get the relevant data in a data.frame. Once you get it into that format, generally, it is then easy as pie.
Leave a Comment