Instead of the normal plot function I am using ggplot2 to create NMDS plots. I would like to display groups in the NMDS plot using the function ordiellipse() from the vegan package.
Example data:
library(vegan)
library(ggplot2)
data(dune)
# calculate distance for NMDS
sol <- metaMDS(dune)
# Create meta data for grouping
MyMeta = data.frame(
sites = c(2,13,4,16,6,1,8,5,17,15,10,11,9,18,3,20,14,19,12,7),
amt = c("hi", "hi", "hi", "md", "lo", "hi", "hi", "lo", "md", "md", "lo",
"lo", "hi", "lo", "hi", "md", "md", "lo", "hi", "lo"),
row.names = "sites")
# plot NMDS using basic plot function and color points by "amt" from MyMeta
plot(sol$points, col = MyMeta$amt)
# draw dispersion ellipses around data points
ordiellipse(sol, MyMeta$amt, display = "sites", kind = "sd", label = T)
# same in ggplot2
NMDS = data.frame(MDS1 = sol$points[,1], MDS2 = sol$points[,2])
ggplot(data = NMDS, aes(MDS1, MDS2)) +
geom_point(aes(data = MyMeta, color = MyMeta$amt))
How can I add ordiellipse to the NMDS plot created with ggplot2?
Didzis Elferts’ answer below works great. Thank you! However, I am now interested in plotting the following ordiellipse to the NMDS plot created with ggplot2:
ordiellipse(sol, MyMeta$amt, display = "sites", kind = "se", conf = 0.95, label = T)
Unfortunately, I don’t understand enough about how the veganCovEllipse function works to be able to adjust the script myself.
First of all, I added column group to your NMDS data frame.
Second data frame contains mean MDS1 and MDS2 values for each group and it will be used to show group names on plot
Data frame
df_ellcontains values to show ellipses. It is calculated with functionveganCovEllipsewhich is hidden inveganpackage. This function is applied to each level of NMDS (group) and it uses also functioncov.wtto calculate covariance matrix.Now ellipses are plotted with function
geom_path()andannotate()used to plot group names.Idea for ellipse plotting was adopted from another stackoverflow question.
UPDATE – solution that works in both cases
First, make NMDS data frame with group column.
Next, save result of function
ordiellipse()as some object.Data frame
df_ellcontains values to show ellipses. It is calculated again with functionveganCovEllipsewhich is hidden inveganpackage. This function is applied to each level of NMDS (group) and now it uses arguments stored inordobject –cov,centerandscaleof each level.Plotting is done the same way as in previous example. As for the calculating of coordinates for elipses object of
ordiellipse()is used, this solution will work with different parameters you provide for this function.