Plotting Raster Data in python using Rasterio¶
What is rasterio?¶
Rasterio is an open-source Python library for reading, writing, and manipulating geospatial raster data. It provides a high-level interface to the GDAL (Geospatial Data Abstraction Library) library, which is widely used for working with geospatial data. With Rasterio, you can read and write raster data in various formats, perform operations such as cropping and resampling, and extract information from raster datasets such as the spatial extent and resolution. It also provides support for handling different coordinate reference systems (CRS) and handling geospatial metadata. The library is designed to be easy to use and provides a simple, Pythonic interface to raster data that makes it a popular choice for geospatial data processing and analysis.
import rasterio
import matplotlib.pyplot as plt
# Open the raster data using rasterio
with rasterio.open("Etopo.tif") as src:
data = src.read(1)
The code block opens the raster data file Etopo.tif
using the rasterio.open
function. The with statement is used to open the file, which will automatically close the file when the block of code is finished executing.
The src
object is a Rasterio dataset object that provides access to the data and metadata of the Etopo.tif
file. The read method is called with the argument 1
to read the first band of data from the file. The result is stored in the data
variable, which is a NumPy array that contains the raster values for the first band of the file.
With the data stored in the data
variable, you can perform various operations and analysis on the raster data, such as plotting or transforming the data to a different coordinate reference system
fig = plt.figure(figsize=[12,8])
# Plot the raster data using matplotlib
plt.imshow(data)
plt.show()
This code block creates a figure using the matplotlib.pyplot
library and sets its size to [12, 8]
inches. The plt.imshow
function is then used to display the data variable, which contains the raster values for the first band of the Etopo.tif
file.
The plt.imshow
function is a Matplotlib function that displays an image or array of data as an image, using color to represent the values of the data. The data variable is passed as the input to plt.imshow, which will display the raster data as an image.
Finally, the plt.show
function is used to display the figure on the screen. This will display the raster data as an image in a Matplotlib window.
Adding color map to raster data¶
In Matplotlib, cmap
(short for colormap) is a parameter in various plotting functions that specifies the colormap to use for plotting values. A colormap is a mapping of values to colors, and colormaps can be used to give visual representations of scalar quantities, such as temperature or density, in a plot. Matplotlib provides a large number of colormaps, and users can also define their own custom colormaps.
Here are few colormap we are going to use