I have a dataset containing longitude, latitude and a value column showing humidity, about 300 rows in length. Each point shows the humidity for a different location. I would like to plot all of them on a map and colour them according to their value (such as in gradient colours) and add a legend. It is a bit similar to the question here, but I can't get it to work. The code is basically there but only the colouring and displaying it properly in a legend does not really work. The points represent a line in Africa and the humidity values have been originally extracted from a raster dataset and they contain several digits. I created some sample data to illustrate where I am stuck.
library("maps")
library("raster")
# create sample data
lon <- seq(from=35.6, to=43.2, by=0.2)
lat <- seq(from=10.5, to=22.2, by=0.2)
humidity <- runif(59, min=9.6, max=13.5)
data <- data.frame(lon,lat, humidity)
colfunc<-colorRampPalette(c("dodgerblue2","khaki","orangered")) # create colours
map('world', xlim = c(20, 80), ylim = c(5, 30), lwd=0.5, col = "grey95", fill = T, interior = FALSE)
title("specific humidity along line")
map.axes()
points(data$lon, data$lat, cex=.5, pch=19, col=colfunc(100))
legend("topleft",title="q (g/kg)",legend=c(11,11.5,12,12.5,13),col =colfunc(100), pch=20)
The resulting plot looks like this:
Something is clearly wrong with the legend, I would like to have a few points shown in the legend with the corresponding colour and value or even use a nice colourbar. I am not sure why the colour in the legend is just blue. I also suspect that the line of points is not coloured according to their actual value and just displaying the whole colour gradient. Thanks for any suggestions!
UPDATE with code from Alex:
n <- 10
colfunc<-colorRampPalette(c("dodgerblue2","khaki","orangered")) # create colours
mycol <- function(x, myrange, n=10) round( 1+(x-myrange[1])/diff(myrange) * (n-1))
map('world', xlim = c(20, 80), ylim = c(5, 30), lwd=0.5, col = "grey95", fill = T, interior = FALSE)
title("specific humidity along line")
map.axes()
points(data$lon, data$lat, cex=.5, pch=19, col=colfunc(n)[mycol(humidity, range(humidity), n)])
mylist <- c(10,11,11.5,12,12.5,13)
legend("topleft",title="q (g/kg)",legend=mylist,col = colfunc(n)[mycol(mylist,range(humidity), n)], pch=20)
That generates this plot:
Points are overlapping and it is hard to see the overall values of the points, is there any way to colour the points according to a defined range using the colourramp? Such as "red" for values 10 to 11, "green" for 11 to 12 and so on?