Creating a Contour Map Using Python PyVista
Last Updated :
26 Jul, 2024
Contour maps are essential for visualizing three-dimensional data on a two-dimensional plane, often used in fields like geography, meteorology, and various scientific disciplines. PyVista, a powerful Python library built on top of the Visualization Toolkit (VTK), offers an intuitive interface for creating and visualizing such maps. In this article, we'll explore how to create a contour map using PyVista, specifically within a Google Colab environment.
Key Features of PyVista
- 3D Visualization: Simple tools for creating complex 3D plots.
- Mesh Analysis: Functions for detailed analysis and manipulation of mesh data.
- Interactivity: Interactive plotting for enhanced data exploration.
- Integration: Seamless integration with NumPy, Pandas, and other scientific libraries.
Setting Up PyVista
To begin using PyVista, we can ensure that installed Pyvist. If not use the below command to install the PyVista.
pip install pyvista
It requires VTK (Visualization Toolkit) to be installed, which is typically handled automatically during the PyVista installation.
Preparing Data for Contour Maps
# Create a simple grid with scalar data
x = np.linspace(0, 10, 100)
y = np.linspace(0, 10, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X) * np.cos(Y)
In this example, we prepare the synthetic data using NumPy:
- numpy can be used to create the 1D arrays ('x', 'y') which are then meshgrid-ed to form the 2D arrays.
- z is computed as the sin(x) * cos(Y), it can provide the scalar values for the elevation.
Creating the StructuredGrid with PyVista
We can work with the data and create the structured grid:
# Create a PyVista structured grid
grid = pv.StructuredGrid(X, Y, Z)
- StructuredGrid: pv.StructuredGrid(X, Y, Z): It can be creates the structured grid directly from the meshgrid arrays X, Y and scalar Z.
Adding the Scalar Data to Grid
In PyVista, scalar data can be associated with the points or cells of grid. Here, we can associate the scalar data('Elevation') with the points of the grid.
# Add scalar data to the grid
grid.point_data["Elevation"] = Z.ravel()
- Z.ravel(): It can flattens the 2D z array into the 1D array to match the number of the points in grid.
Generating Contour Maps
We can generate the contours based on the scalar data('Elevation') added to the grid.
# Define the number of contour levels
contour_levels = 10
# Generate contours using the scalar data
contours = grid.contour(contour_levels, scalars="Elevation")
- grid.contour(contour_levels, scalars="Elevation"): It can be creates the contour lines('contours') based on the scalar data('Elevation') with specified number of the contour_levels.
Customizing Contours and Plotting
PyVista allows customization of the plot settings such as the colors, opacity and line widths:
# Create a plotter object
plotter = pv.Plotter()
# Add the structured grid and contours to the plotter
plotter.add_mesh(grid, opacity=0.5, color='lightgrey')
plotter.add_mesh(contours, color='blue', line_width=2)
# Show the plot
plotter.show()
- plotter.add_mesh(grid, opacity=0.5, color='lightgrey'): It can be adds the structured grid to the plotter with specified opacity and color.
- plotter.add_mesh(contours, color='blue', line_width=2): It can be adds the generated contours to the plotter with specified color and line width.
Complete Code
Example 1: Creating a Contour Map with Synthetic Data
Python
# Import Libraries
import pyvista as pv
import numpy as np
import matplotlib.pyplot as plt
# Define grid size
n = 100
x = np.linspace(-10, 10, n)
y = np.linspace(-10, 10, n)
x, y = np.meshgrid(x, y)
# Define the surface using a mathematical function
z = np.sin(np.sqrt(x**2 + y**2))
# Create a PyVista grid object
grid = pv.StructuredGrid(x, y, np.zeros_like(z))
# Add the z-values as scalars to the grid
grid['scalars'] = z.ravel(order='F')
# Generate contour lines
contours = grid.contour(isosurfaces=10)
# Create a plotter object
plotter = pv.Plotter()
# Add the surface and contours to the plotter
plotter.add_mesh(grid, scalars='scalars', cmap='viridis')
plotter.add_mesh(contours, color='black', line_width=1)
# Add a color bar
plotter.add_scalar_bar(title='Scalar Value')
# Show the plot
plotter.show()
Output:
Example 2: Creating a Contour Map with Real-World Elevation Data
Python
# Import Libraries
import pyvista as pv
import numpy as np
import matplotlib.pyplot as plt
# Load a DEM dataset from PyVista's examples
dem = pv.examples.download_st_helens()
# Generate contour lines
contours = dem.contour(isosurfaces=20)
# Create a plotter object
plotter = pv.Plotter()
# Add the DEM surface and contours to the plotter
plotter.add_mesh(dem, cmap='terrain')
plotter.add_mesh(contours, color='black', line_width=1)
# Add labels and show the plot
plotter.add_scalar_bar(title='Elevation (m)')
plotter.show()
Output:
1. How can i adjust the number of contour levels?
We can modify the contour_levels variable to increase or decrease the number of the contour lines displayed.
2. How can i adjust the contour levels to better the represent my data?
We can adjust the contour_levels parameter in the grid.contour(contour_levels, scalars='Elevation') to increase the number of the contour lines generated. Higher levels can provide more detail, while fewer levels simplify the visualization.
3. Can i customize the apperance of the contour lines such as the color and line thickness?
Yes, we can customize the apperance of the contour lines using the PyVista's plotting capabilities. For example, use the plotter.add_mesh(contours, color='blue', line_width=2) to change the lines color to blue with a line width of the 2 units.
4. What if my dataset has irregular dimensions or missing the data points?
PyVista's StructuredGrid can be expects the regular grid dimensions(X, Y, Z arrays) where all the dimensions match exactly. We can ensure that X,Y and Z arrays have the same shape and are correctly aligned to avoid the errors like ValueError: Input point array shapes must match exactly.
5. How can i add the labels or annotations to contour maps for the better interpretation?
PyVista can be allows adding the annotations and labels to plots using its plotting the capabilities. We can annotate specific contour lines or add the color legends to indicate the scalar values represented by the each contour.
Conclusion
Contour maps are valuable tools for visualizing the spatial data and it can be allowing the insights into patterns and gradients. PyVista simplifies the creation and customization of the contour plots, making it accessible for the scientific visualization and data analysis tasks.
Similar Reads
Find and Draw Contours using OpenCV | Python
Contours are defined as the line joining all the points along the boundary of an image that are having the same intensity. Contours come handy in shape analysis, finding the size of the object of interest, and object detection. OpenCV has findContour() function that helps in extracting the contours
2 min read
Contour Plot using Matplotlib - Python
Contour plots also called level plots are a tool for doing multivariate analysis and visualizing 3-D plots in 2-D space. If we consider X and Y as our variables we want to plot then the response Z will be plotted as slices on the X-Y plane due to which contours are sometimes referred as Z-slices or
2 min read
Introduction to PyVista in Python
Pyvista is an open-source library provided by Python programming language. It is used for 3D plotting and mesh analysis. It also provides high-level API to simplify the process of visualizing and analyzing 3D data and helps scientists and other working professionals in their field to visualize the d
4 min read
3D Contour Plotting in Python using Matplotlib
Matplotlib was introduced keeping in mind, only two-dimensional plotting. But at the time when the release of 1.0 occurred, the 3d utilities were developed upon the 2d and thus, we have 3d implementation of data available today! The 3d plots are enabled by importing the mplot3d toolkit. Let's look a
2 min read
Carpet Contour Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization libra
2 min read
Ternary contours Plot using Plotly in Python
A Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization libra
3 min read
Create Air Canvas using Python-OpenCV
Ever wanted to draw your imagination by just waving your finger in the air. In this post, we will learn to build an Air Canvas which can draw anything on it by just capturing the motion of a colored marker with a camera. Here a colored object at the tip of the finger is used as the marker.We will be
6 min read
How to Draw a Circle Using Matplotlib in Python?
A Circle is a mathematical figure formed by joining all points lying on the same plane and are at equal distance from a given point. We can plot a circle in python using Matplotlib. There are multiple ways to plot a Circle in python using Matplotlib. Method 1: Using matplotlib.patches.Circle() funct
3 min read
Donut Chart using Matplotlib in Python
Prerequisites: Pie Chart in matplotlib Donut charts are the modified version of Pie Charts with the area of center cut out. A donut is more concerned about the use of area of arcs to represent the information in the most effective manner instead of Pie chart which is more focused on comparing the pr
4 min read
Contour Detection with Custom Seeds using Python - OpenCV
This article discusses how we can dynamically detect contours by clicking on the Image and assign different colors to different parts of the image. Contours are a very useful tool for shape analysis and object detection and recognition. This program uses OpenCV, Numpy, and Matplotlib libraries. It a
3 min read