7

I want to have black lines around each cell of a raster. Below is the example data. I mean, instead of this frame/borderless cells

enter image description here

I want this(cells with borders)

enter image description here How can I achieve this?

 library(raster)
 require(graphics)
 require(grDevices)
 library(colorRamps)

 data<-matrix(c(1,0.4,0.5,0.8,-0.9,0.3,-0.89,-0.62,-0.33),ncol=3)

  r <- raster(nrows=dim(data)[1],ncols=dim(data)[2],
               xmn=-1,xmx=1,ymn=-1,ymx=1)
  r[]<-data
  setValues(r,factor(data))
  plot(r,col=c(topo.colors(200)),axes=FALSE,box=FALSE)
zx8754
  • 52,746
  • 12
  • 114
  • 209
Novice
  • 307
  • 2
  • 11
  • 2
    Your code current does not run. `r[] <- numeric ` produces an error. Also, `setValues()` needs to be assigned to something. – bdemarest Jul 25 '15 at 19:04
  • Of course-thanks! I replaced `numeric` with `data`. Now it should work! – Novice Jul 25 '15 at 22:10

2 Answers2

8

You can use rasterToPolygons:

plot(r, col=c(topo.colors(200)), axes=FALSE, box=FALSE)
plot(rasterToPolygons(r), add=TRUE, border='black', lwd=1) 
Jota
  • 17,281
  • 7
  • 63
  • 93
5

If you are open to using ggplot2, I offer a possible solution using geom_tile(). Pixels can be outlined by using the colour argument to geom_tile. The drawback is that your data may need some re-formatting to use with ggplot2.

library(ggplot2)
library(reshape2)

dat = melt(volcano[26:40, 26:40])

p = ggplot(dat, aes(x=Var1, y=Var2, fill=value)) +
    geom_tile(colour="grey20") +
    scale_fill_gradientn(colours = terrain.colors(10))

ggsave("tile_plot.png", plot=p, height=6, width=7, dpi=150)

enter image description here

bdemarest
  • 14,397
  • 3
  • 53
  • 56