Contour Plot of Test Function
A popular plot for two-dimensional functions is a contour plot.
This plot creates a flat representation of the objective function outputs for each x and y coordinate where the color and contour lines indicate the relative value or height of the output of the objective function.
This is just like a contour map of a landscape where mountains can be distinguished from valleys.
This can be achieved using the contour() Matplotlib function that takes the mesh grid and the evaluation of the mesh grid as input directly.
We can then specify the number of levels to draw on the contour and the color scheme to use. In this case, we will use 50 levels and a popular “jet” color scheme where low-levels use a cold color scheme (blue) and high-levels use a hot color scheme (red).
create a contour plot with 50 levels and jet color scheme
pyplot.contour(x, y, results, 50, alpha=1.0, cmap=‘jet’)
show the plot
pyplot.show()
create a contour plot with 50 levels and jet color scheme
pyplot.contour(x, y, results, 50, alpha=1.0, cmap=‘jet’)
show the plot
pyplot.show()
Tying this together, the complete example of creating a contour plot of the two-dimensional objective function is listed below.
contour plot for 2d objective function
from numpy import arange
from numpy import meshgrid
from matplotlib import pyplot
objective function
def objective(x, y):
return x2.0 + y2.0
define range for input
r_min, r_max = -5.0, 5.0
sample input range uniformly at 0.1 increments
xaxis = arange(r_min, r_max, 0.1)
yaxis = arange(r_min, r_max, 0.1)
create a mesh from the axis
x, y = meshgrid(xaxis, yaxis)
compute targets
results = objective(x, y)
create a contour plot with 50 levels and jet color scheme
pyplot.contour(x, y, results, 50, alpha=1.0, cmap=‘jet’)
show the plot
pyplot.show()
Running the example creates the contour plot.
We can see that the more curved parts of the surface around the edges have more contours to show the detail, and the less curved parts of the surface in the middle have fewer contours.
We can see that the lowest part of the domain is the middle, as expected.