Search code examples
rlatitude-longitudeheatmaplevels

Make heatmap of presence of levels for a dataframe


I have a dataframe containing biological observations. For each observations, i have latitude, longitude and species name.

What i want to do is an heatmap of the biodiversity/species richness (number of different species at a location). I don't want to do an heatmap of my observation but the diversity of species in it.

I am sure that it exist an elegant way to do it. That's why i need your help.

Here is my data as exemple : https://filesender.ens-lyon.fr/?vid=1de55ca8-7e1d-6b29-4a28-00004e605af1

Otherwise i plan to :

  • divide a map into square
  • check presence or absence of levels in a subseted data that fit a square
  • Add the number of species of this square into a data frame (a kind of length(levels(subset(data,lon and lat in the square))))
  • Heatmap plot of my dataframe of levels count I don't really like this method because of the dividing of my map which will complexify my code a lot.

Thanks you for reading. I hope that your eyes are not bleeding because of my english.

Akim


Solution

  • Probably not the most elegant way, but it makes a heatmap. I used symmetrical breaks, but you can adjust them individually (and also the bin-width).You can use heatmaps.2 instead to get automatic legend.

    require(plyr)
    mydf <- read.csv('data_observation.csv')
    #Bin longitude and latitude
    lat_breaks <- seq(-160,175,5)
    long_breaks <- seq(-160,175,5)
    mydf$lat <- cut(mydf$latitude,breaks = lat_breaks, labels=F)
    mydf$long <- cut(mydf$longitude,breaks = long_breaks, labels=F)
    #Aggregate observations 
    mydf <- ddply(mydf, .(lat,long), summarize, div=length(unique(specname)))
    #Build the map
    mymap <- cbind(lat=rep(1:length(lat_breaks), each=length(long_breaks)), 
                   long=rep(1:length(long_breaks), length(lat_breaks)))
    mymap <- merge(mymap,mydf, by=c('lat','long'), all.x=T)
    mymap <-dcast(mymap, lat~long, drop = F,)[,-1]
    #Plot
    heatmap(as.matrix(mymap),Rowv = NA,Colv = NA, scale = 'none', 
            col=topo.colors(256),labRow = lat_breaks, labCol = long_breaks,
            xlab='latitude', ylab='longitude')
    

    enter image description here