-1

I cannot get my data plotted properly with R. I got measurements from a football field and I did not fill measurements for each grid.

Here is my dataset contour_map_R.csv at https://db.tt/1L7cxilB

It looks like this using image function to plot it.

enter image description here

Any one can provide an example to create a filled contour plot?

Thanks a lot!

Kuo-Hsien Chang
  • 925
  • 17
  • 40

1 Answers1

2

As stated in the comments you need to have complete data before you can calculate contours. Therefore you have to interpolate or replace your missing values in some way that makes sense in your case. I've provided a couple of options below, but you'd need to come up with rationale for using one method over another, and whether a more sophisticated geostatistical approach might be warranted. Furthermore you could interpolate to a finer grid than you currently have as well to produce a smoother result (at the expense of potentially making up data).

d <- read.csv("contour_map_R.csv")

library(raster)
r <- raster(as.matrix(d))

contour(r)

v <- getValues(r)
xy <- xyFromCell(r, 1:ncell(r))

##  Interpolate using a thin-plate spline:
library(fields)
tps <- Tps(xy, v)

tp <- interpolate(r, tps)
plot(tp)
contour(tp, add=T)

thin-plate spline

##  Alternatively, interpolate using nearest idw():
library(gstat)

dxy <- data.frame(x=xy[,1], y=xy[,2], v)
dxy <- dxy[complete.cases(dxy),]
id <- gstat(formula = v~1, locations = ~x+y, data=dxy)

ip <- interpolate(r, id)
plot(ip)
contour(ip, nlevels=5, add=T)

IDW

If that's what you were looking for you can get filled contours by using the filledContour() function on the interpolated rasters (tp or ip).

Forrest R. Stevens
  • 3,435
  • 13
  • 21
  • Thank a lot!! How to set the xlim and ylim from 0 to 1?? – Kuo-Hsien Chang Jun 04 '15 at 19:19
  • You essentially need to have the plot area match your raster dimensions. This can be non-trivial, but this [question/answer](http://stackoverflow.com/questions/17214469/r-crop-raster-data-and-set-axis-limits) will hopefully give you a good place to start. – Forrest R. Stevens Jun 05 '15 at 01:00