Tuesday, December 10, 2019

Displaying Rasters in Jupyter Notebooks

Rasters in Jupyter

It's the easy stuff that trips you up the most, right? Here I was, wanting to talk about creating rasters in R and Python when I realized that I didn't have a great handle on how to display them. Turns out that it is very simple to do. (GeoTIFF generated from code taken from Jared's excellent gdal/ogr cookbook.)

In Python

Use GDAL and Matplotlib

from matplotlib import pyplot
%matplotlib inline
from osgeo import gdal

img = gdal.Open('test.tif').ReadAsArray()
im = pyplot.imshow(img)

python<em>jupyter</em>geotif

In R

Use the raster library's built-in plot() function

library(raster)
library(repr)

options(repr.plot.width=4, repr.plot.height=3)
img_file <- raster("test.tif")
plot(img_file)

NOTE: repr is used solely to control the output size of the plot. Without it, the image is rather large.

R<em>jupyter</em>geotif

No comments: