This post documents the method of visualizing contours of functions and their 3D images.
The function plotted in this example is:
1. Grid points
Before plotting the curve, it is important to understand the plotting of grid points. For example, if you plot a 3x3 grid, then you need 9 coordinate points:
(0,2)-----(1,2)-----(2,2)
(0,1)-----(1,1)-----(2,1)
(0,0)-----(1,0)-----(2,0)
Represent its x-axis and y-axis coordinates separately:
# x-axis. [[0, 1, 2], [0, 1, 2], [0, 1, 2]] # y-axis. [[0, 0, 0], [1, 1, 1], [2, 2, 2]]
Grid points can be generated in numpy using ():
import numpy as np import as plt # 10x10 x = (-1.5, 1.5, num=10) y = (-1.5, 1.5, num=10) # generate grid X, Y = (x, y) (X, Y, marker='.', linestyle='') (True) ()
2. Contour lines
The data needed to draw the contour line are the coordinate position of the point (x, y) and the height of the coordinate z. The height z is calculated by bringing the coordinate point (x, y) into the function f ( x , y ) f(x, y) f(x, y) f(x, y), which is calculated in thematplotlib
It can be drawn using () in the
import numpy as np import as plt x = (-1.5, 1.5, num=100) y = (-1.5, 1.5, num=100) X, Y = (x, y) f = X * (-X**2 - Y**2) fig = () (-1.5, 1.5) (-1.5, 1.5) # draw ax = (X, Y, f, levels=10, cmap=) # add label (ax, inline=True) # ('') ()
# add color (X, Y, f, levels=10, cmap=) # () # ('') ()
For more api parameters please refer toofficial document。
3. Three-dimensional images
The drawing of the 3D image of the function requires the same data as the contour lines, i.e., the coordinate position (x, y) and the height z of the coordinates, which can be drawn in matplotlib using mpl_toolkits.mplot3d:
import numpy as np import as plt from mpl_toolkits.mplot3d import Axes3D x = (-1.5, 1.5, num=100) y = (-1.5, 1.5, num=100) X, Y = (x, y) f = X * (-X**2 - Y**2) fig = () ax = Axes3D(fig) (-1.5, 1.5) (-1.5, 1.5) ax.plot_surface(X, Y, f, cmap=) # ('') ()
to this article on the python, Matplotlib plotting function based on the contour and three-dimensional image of the article is introduced to this, more related Matplotlib plotting function of the contour and three-dimensional image of the contents of the search for my previous posts or continue to browse the following related articles I hope that you will support me in the future more!
For more information on the use of mpl_toolkits.mplot3d you can refer to theofficial document;
For more color matching see matplotlib's colormapOfficial Handbook。