How To Draw A Contour Using Matplotlib package


 A simple contour plot example with matplotlib
This program produces a contour plot of a function, labels the contours and provides some custom styling for their colour choices too. For you to understand this perfectly, you need to go through the process step by step and if you have any problem too, comment it in the comment box and I reply to your problem.
There are different ways of visualizing data in python. But this particular post is about using the python package called the matplotlib. To check whether you have matplotlib installed on your environment, you first need to import the matplotlib module. To import a module means that you are calling that module into the current or working environment.
e.g import math as m means that, bring math module into my working environment and assign it to m so that whenever I call m, the math is being called.
To import the matplotlib to the environment too we follow the same procedure above.
The following program is to plot contours of particular contour interval


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

X = np.linspace(0,1,100)
Y = X.copy()
X, Y = np.meshgrid(X, Y)
alpha = np.radians(25)
cX, cY = 0.5, 0.5sigX, sigY = 0.2, 0.3rX = np.cos(alpha) * (X-cX) - np.sin(alpha) * (Y-cY) + cX
rY = np.sin(alpha) * (X-cX) + np.cos(alpha) * (Y-cY) + cY

Z = (rX-cX)*np.exp(-((rX-cX)/sigX)**2) * np.exp(- ((rY-cY)/sigY)**2)
fig = plt.figure()
ax = fig.add_subplot(111)

# Reversed Greys colourmap for filled contourscpf = ax.contourf(X,Y,Z, 20, cmap=cm.Greys_r)
# Set the colours of the contours and labels so they're white where the# contour fill is dark (Z < 0) and black where it's light (Z >= 0) 
#colours = ['w' if level<0 else 'k' for level in cpf.levels]cp = ax.contour(X, Y, Z, 20, colors='r')
ax.clabel(cp, fontsize=12, colors='b')
plt.show()





This is the outcome






You can watch the video below to help you get the visual aspect


No comments:

Post a Comment