Raster layer plot in ggplot

3,651 views
Skip to first unread message

Swagath

unread,
Jul 15, 2011, 9:46:14 AM7/15/11
to ggplot2
Dear list members,

I am learning to use ggplot2 for my spatial data. I have a following
raster layer i created from a txt file:

x <- as.matrix(read.table("sample2.txt", header=FALSE))
myraster<-raster(x,xmn=-10.311630235357, xmx=31.1883698,
ymn=35.110501339805, ymx=71.1105, crs="+proj=longlat +datum=WGS84")
> myraster
class : RasterLayer
dimensions : 72, 84, 6048 (nrow, ncol, ncell)
resolution : 0.4940476, 0.5 (x, y)
extent : -10.31163, 31.18837, 35.1105, 71.1105 (xmin, xmax,
ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84
values : in memory
min value : 0.02663409
max value : 1.760257

and i am trying to plot this using ggplot2. Can anyone tell me how
this can be done.

Thanks a lot for your time.

Thanks,
Swagath

Pierre Roudier

unread,
Jul 17, 2011, 8:00:10 PM7/17/11
to Swagath, ggplot2
Swagath,

Raster* objects can be directly manipulated by ggplot2 (yet?).

You need to convert your Raster object ito a data.frame first, then
plot it using geom_tile().

Note that this would be very inefficient - or even impossible - with a
big raster, as it is vector graphics.

Consider the following example (please always provide with a
reproducible example):

library(raster)
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
proj4string(meuse.grid) <- CRS("+init=epsg:28992")
gridded(meuse.grid) = TRUE
r <- raster(meuse.grid, layer=5)
r

# To convert your RasterLayer to a data.frame, you need to convert it to
# a SpatialPixelsDataFrame first
r.spdf <- as(r, "SpatialPixelsDataFrame")
r.df <- as.data.frame(r.spdf)
head(r.df)

# then you can use ggplot2 to plot that object
library(ggplot2)
g <- ggplot(r.df, aes(x=x, y=y)) + geom_tile(aes(fill = V1)) + coord_equal()
print(g)

HTH,

Pierre

2011/7/16 Swagath <swagat...@gmail.com>:

> --
> You received this message because you are subscribed to the ggplot2 mailing list.
> Please provide a reproducible example: http://gist.github.com/270442
>
> To post: email ggp...@googlegroups.com
> To unsubscribe: email ggplot2+u...@googlegroups.com
> More options: http://groups.google.com/group/ggplot2
>

--
Scientist
Landcare Research, New Zealand

swagath navin

unread,
Jul 18, 2011, 2:06:06 PM7/18/11
to Pierre Roudier, ggplot2
Hi Pierre,

Thank you very much for your help.

Thanks,
Swagath
Reply all
Reply to author
Forward
0 new messages