Search code examples
rggplot2colorseuclidean-distancevegan

Using colors to represent distance measures in R


I have a dataframe of species abundances that include samples from multiple georeferenced points. I am using distance-based ordiantions to represent similarities in species composition, such as the example:

sample <- c(1:5)
lon <- c(9,22,31,20,12)
lat <- c(20,22,30,48,53)
sp1 <- c(5,6,14,25,30)
sp2 <- c(0,0,0,3,4)
sp3 <- c(17,12,7,2,2)
sp4 <- c(1,0,2,0,1)
d <- data.frame(sample, lon, lat, sp1, sp2, sp3, sp4)

library(vegan)
library(ggplot2)
library(Rmisc)

dist <- vegdist(d[,4:7], method="euclidean")
PCoA <- as.data.frame(scores(cmdscale(dist)))

co <- ggplot(d, aes(x=lon, y=lat)) + geom_point() + ggtitle("Coordinates") + theme_bw() + geom_text(label=sample, hjust = 0, nudge_x = 0.5)
pc <- ggplot(PCoA, aes(x=Dim1, y=Dim2)) + geom_point() + ggtitle("PCoA Euclidean") + theme_bw() + geom_text(label=sample, hjust = 0, nudge_x = 0.5)

m <- matrix(1:2, byrow=T, nrow=1)
multiplot(co, pc, layout=m)

I would like make a scaterplot with the coordinates, but using colors to represent the ordination scores (that is, it's 1st and 2nd axis) or at least to represent the distance measure (Euclidean or others) and generate this result: result I want

I tried to associate a color palete, but I do not know how to do that for a bidimensional color space (that is, based on my PCoA ordination). Does anybody know how to do that?


Solution

  • You can use the colorplaner library (see here):

    library(colorplaner)
    gg_data <- cbind(d[, c("sample","lon","lat")], PCoA[,c("Dim1","Dim2")])
    
    
    ggplot(gg_data, aes(x = lon, y = lat, color = Dim1, color2 = Dim2)) + 
      geom_point() + 
      scale_color_colorplane()  + 
      ggtitle("Coordinates") + 
      theme_bw() + 
      geom_text(label=sample, hjust = 0, nudge_x = 0.5)
    

    This gives:

    enter image description here