This is a quick introduction to GRASS GIS in a Jupyter Notebook using the grass.jupyter
package and the Python scripting language. The grass.jupyter
package shortens the launch of GRASS GIS in Jupyter Notebook and provides several useful classes for creating, displaying and saving GRASS GIS maps. This notebook can be directly compared with basic_example.ipynb to see how the package improves the integration of GRASS GIS and Jupyter Notebooks.
The grass.jupyter
package was written as part of Google Summer of Code in 2021. For more information, visit the wiki page.
Examples here are using a sample GRASS GIS dataset for North Carolina, USA. The dataset is included in this environment.
To run the selected part which is called a cell, hit Shift + Enter
.
There are several ways to use GRASS GIS. When using Python in a notebook, we usually find GRASS GIS Python packages first, import them, initialize GRASS GIS session, and set several variables useful for using GRASS GIS in a notebook.
# Import Python standard library and IPython packages we need.
import os
import subprocess
import sys
# Ask GRASS GIS where its Python packages are.
gisbase = subprocess.check_output(["grass", "--config", "path"], text=True).strip()
os.environ["GISBASE"] = gisbase
sys.path.append(os.path.join(gisbase, "etc", "python"))
# Import the GRASS GIS packages we need.
import grass.script as gs
import grass.jupyter as gj
# Start GRASS Session
gj.init("../../data/grassdata", "nc_basic_spm_grass7", "user1")
Set computational region and create multiple buffers in given distances around lakes represented as raster:
gs.parse_command("g.region", raster="lakes", flags="pg")
gs.run_command("r.buffer", input="lakes", output="lakes_buff", distances=[60, 120, 240, 500])
# Start a GrassRenderer
img = gj.GrassRenderer()
# Add a raster and vector to the map
img.d_rast(map="lakes_buff")
img.d_legend(raster="lakes_buff", range=(2, 5), at=(80, 100, 2, 10))
# Display map
img.show()
Create a negative buffer around state boundary represented as a vector. Vector modules typically don't follow computational region, but we set it to inform display modules about our area of interest.
gs.run_command("v.buffer", input="boundary_state", output="buffer", distance=-10000)
gs.parse_command("g.region", vector="boundary_state", flags="pg")
# Start another GrassRenderer
img2 = gj.GrassRenderer()
# Add vector layers and legend
img2.d_vect(map="boundary_state", fill_color="#5A91ED", legend_label="State boundary")
img2.d_vect(map="buffer", fill_color="#F8766D", legend_label="Inner portion")
img2.d_legend_vect(at=(10, 35))
# Display map
img2.show()
print(gs.read_command("g.list", type="all"))
print(gs.read_command("g.search.modules", flags="g"))