This tutorial offers a quick look at some common 2d and 3d Visualization available in python. This tutorial is meant to give anyone a quick start in matplotlib and mayavi.mlab.
The tutorial was written as part of CSRP program of AeSIAA which the author is participating as a mentor to few aeronautical students.
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
a=np.random.rand(10,3)
x=a[:,0]
y=a[:,1]
z=np.linspace(0,2*np.pi,10)
fig = plt.figure()
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.plot(a);
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(a);
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(a);
axes.set_title("Our First Plot");
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.plot(a);
axes.set_title("Our First Plot");
axes.set_xlabel("alpha ");
axes.set_ylabel("beta ");
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # left, bottom, width, height (range 0 to 1)
axes.plot(a,linewidth=3)
axes.set_title("Our First Plot")
axes.set_xlabel("alpha ")
axes.set_ylabel("beta ")
<matplotlib.text.Text at 0x10656c7d0>
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(a[:,0],a[:,2], "o")
axes.set_title("X Y plot")
axes.set_xlabel("alpha ")
axes.set_ylabel("beta ")
<matplotlib.text.Text at 0x1066973d0>
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(a[:,0],a[:,2], "o")
axes.set_title("X Y plot")
axes.set_xlabel("alpha ")
axes.set_ylabel("beta ")
axes.grid(True)
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(a[:,0],a[:,2], "go")
axes.set_title("X Y plot")
axes.set_xlabel("alpha ")
axes.set_ylabel("beta ")
axes.grid(True)
fig = plt.figure(figsize=(10,4))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
axes.plot(a[:,0],a[:,2], "go");
axes.set_title("X Y plot");
axes.set_xlabel("alpha ");
axes.set_ylabel("beta ");
axes.grid(True);
axes2 = fig.add_axes([0.2, 0.5, 0.4, 0.3])
axes2.plot(a);
axes2.set_title("mini");
axes2.set_xlabel("a");
axes2.set_ylabel("b");
subplots
is very common, which can be used like this:¶fig, axes = plt.subplots(figsize=(10,4))
axes.plot(a[:,0],a[:,2], "o")
axes.set_title("X Y plot")
axes.set_xlabel("alpha ")
axes.set_ylabel("beta ")
axes.grid(True)
fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,4))
for ax in axes:
ax.plot(a[:,0],a[:,2], "o")
ax.set_title("X Y plot")
ax.set_xlabel("alpha ")
ax.set_ylabel("beta ")
ax.grid(True)
fig, axes = plt.subplots(nrows=4, ncols=1,figsize=(8,10))
for ax in axes:
ax.plot(a[:,0],a[:,2], "o")
ax.set_title("X Y plot")
ax.set_xlabel("alpha ")
ax.set_ylabel("beta ")
ax.grid(True)
fig, axes = plt.subplots(nrows=4, ncols=1,figsize=(8,10))
for ax in axes:
ax.plot(a[:,0],a[:,2], "o")
ax.set_title("X Y plot")
ax.set_xlabel("alpha ")
ax.set_ylabel("beta ")
ax.grid(True)
fig.tight_layout()
fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(10,4))
for ax in axes:
ax.plot(a[:,0],a[:,2], "o")
ax.set_title("X Y plot")
ax.set_xlabel("alpha ")
ax.set_ylabel("beta ")
ax.grid(True)
fig.tight_layout()
fig.savefig("filename.png")
fig.savefig("filename.png",dpi=300)
fig, ax = plt.subplots(figsize=(10,4))
ax.plot(z, z**2, label="y = z**2")
ax.plot(z, z**3, label="y = z**3")
ax.legend(loc=2); # upper left corner
ax.set_xlabel('z')
ax.set_ylabel('y')
ax.set_title('title');
x=z
fig, axes = plt.subplots(1, 3, figsize=(10, 4))
axes[0].plot(x, x**2, x, x**3)
axes[0].set_title("default axes ranges")
axes[1].plot(x, x**2, x, x**3)
axes[1].axis('tight')
axes[1].set_title("tight axes")
axes[2].plot(x, x**2, x, x**3)
axes[2].set_ylim([0, 60])
axes[2].set_xlim([2, 5])
axes[2].set_title("custom axes range");
fig.tight_layout()
fig, axes = plt.subplots(1, 2, figsize=(10,4))
# default grid appearance
axes[0].plot(x, x**2, x, x**3, lw=2)
axes[0].grid(True)
# custom grid appearance
axes[1].plot(x, x**2, x, x**3, lw=2)
axes[1].grid(color='b', alpha=0.5, linestyle='dashed', linewidth=0.5)
fig.tight_layout()
fig, ax1 = plt.subplots(figsize=(10,4))
ax1.plot(x, x**2, lw=2, color="blue")
ax1.set_ylabel(r"area $(m^2)$", fontsize=18, color="blue")
for label in ax1.get_yticklabels():
label.set_color("blue")
ax2 = ax1.twinx()
ax2.plot(x, x**3, lw=2, color="red")
ax2.set_ylabel(r"volume $(m^3)$", fontsize=18, color="red")
for label in ax2.get_yticklabels():
label.set_color("red")
fig.tight_layout()
ax2 = ax1.twinx()
part¶fig, ax = plt.subplots(figsize=(10,4))
ax.plot(x, x**2, x, x**3)
ax.text(5, 10, r"$y=x^2$", fontsize=20, color="blue")
ax.text(4, 160, r"$y=x^3$", fontsize=20, color="green");
def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2)
n = 256
x = np.linspace(-3,3,n)
y = np.linspace(-3,3,n)
X,Y = np.meshgrid(x,y)
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap=plt.cm.hot);
C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5);
plt.clabel(C, inline=1, fontsize=10);
plt.xticks([]), plt.yticks([]);
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
plt.contourf(X, Y, f(X,Y), 8, alpha=.75, cmap=plt.cm.hot);
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5)
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
C = plt.contour(X, Y, f(X,Y), 8, colors='black', linewidth=.5);
plt.clabel(C, inline=1, fontsize=10);
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
C = plt.contour(X, Y, f(X,Y), 8, linewidth=.5);
plt.clabel(C, inline=1, fontsize=10);
x = np.random.rand(20)*10
y = np.random.rand(20)*10
fig, ax = plt.subplots(figsize=(12,6))
ax.bar(range(len(x)), np.sort(y), facecolor='#9999ff',edgecolor='white');
ax.set_title(r"$Bar Chart$");
ax.set_xlabel(r"$\alpha$");
ax.set_ylabel(r"$\beta$");
fig, ax = plt.subplots(figsize=(12,6))
ax.bar(range(len(x)), np.sort(y), facecolor='#9999ff',edgecolor='white');
for xx,yy in zip(range(len(x)),np.sort(y)):
ax.text(xx+0.4, yy+0.05, '%.2f' % yy, ha='center', va= 'bottom');
ax.set_title(r"$Bar Chart$");
ax.set_xlabel(r"$\alpha$");
ax.set_ylabel(r"$\beta$");
hd=np.random.randn(10000)
fig, ax = plt.subplots(figsize=(10,4))
ax.hist(hd, bins=25,color="lightgreen",edgecolor='white');
fig, ax = plt.subplots(1,2,figsize=(10,4))
ax[0].hist(hd, bins=10,color="lightgreen",edgecolor='white',orientation="horizontal");
ax[1].plot(hd,"r.");
fig.tight_layout()
n = 12
X,Y = np.mgrid[0:n,0:n]
T = np.arctan2(Y-n/2.0, X-n/2.0)
R = 10+np.sqrt((Y-n/2.0)**2+(X-n/2.0)**2)
U,V = R*np.cos(T), R*np.sin(T)
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
plt.quiver(X,Y,U,V,R, alpha=.5);
# Remove Ticks
plt.xlim(-1,n), plt.xticks([]);
plt.ylim(-1,n), plt.yticks([]);
quiver(args, *kw) Plot a 2-D field of arrows.
call signatures::
quiver(U, V, **kw)
quiver(U, V, C, **kw)
quiver(X, Y, U, V, **kw)
quiver(X, Y, U, V, C, **kw)
Arguments:
*X*, *Y*:
The x and y coordinates of the arrow locations (default is tail of
arrow; see *pivot* kwarg)
*U*, *V*:
Give the x and y components of the arrow vectors
*C*:
An optional array used to map colors to the arrows
fig, axes = plt.subplots(1, 1, figsize=(10, 4))
plt.axes([0.025,0.025,0.95,0.95])
plt.quiver(X,Y,U,V,R, alpha=.5);
plt.quiver(X,Y,U,V, edgecolor='k', facecolor='None', linewidth=.5);
plt.xlim(-1,n);
plt.xticks([]);
plt.ylim(-1,n);
plt.yticks([]);
Y, X = np.mgrid[-3:3:100j, -3:3:100j]
U = -1 - X**2 + Y
V = 1 + X - Y**2
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
plt.axes([0.025,0.025,0.95,0.95]);
plt.streamplot(X, Y, U, V, density=1, color=U, linewidth=2, cmap=plt.cm.winter);
plt.colorbar();
streamplot(x, y, u, v, density=1, linewidth=None, color=None, cmap=None, norm=None, arrowsize=1, arrowstyle='-|>', minlength=0.1, transform=None, hold=None) Draws streamlines of a vector flow.
*x*, *y* : 1d arrays
an *evenly spaced* grid.
*u*, *v* : 2d arrays
x and y-velocities. Number of rows should match length of y, and
the number of columns should match x.
*density* : float or 2-tuple
Controls the closeness of streamlines. When `density = 1`, the domain
is divided into a 25x25 grid---*density* linearly scales this grid.
Each cell in the grid can have, at most, one traversing streamline.
For different densities in each direction, use [density_x, density_y].
*linewidth* : numeric or 2d array
vary linewidth when given a 2d array with the same shape as velocities.
*color* : matplotlib color code, or 2d array
Streamline color. When given an array with the same shape as
velocities, *color* values are converted to colors using *cmap*.
labels = 'F16', 'Migs', 'Sukhoi', 'F22'
sizes = [23, 34, 44, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'MIGs')
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
i=plt.pie(sizes, labels=labels, )
i=plt.axis('equal')
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
i=plt.pie(sizes, explode=explode, labels=labels, )
i=plt.axis('equal')
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
i=plt.pie(sizes, explode=explode, labels=labels, colors=colors,
startangle=90)
i=plt.axis('equal')
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
i=plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', startangle=90)
i=plt.axis('equal')
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
i=plt.pie(sizes, explode=explode, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
i=plt.axis('equal')
from mpl_toolkits.mplot3d.axes3d import Axes3D
X = np.arange(-5, 5, 0.25)
xlen = len(X)
Y = np.arange(-5, 5, 0.25)
ylen = len(Y)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
fig, axes = plt.subplots(1, 1, figsize=(10, 6))
axes = fig.add_subplot(1,1,1, projection='3d')
surf = axes.plot_surface(X, Y, Z, rstride=1, cstride=1,
linewidth=0.5, antialiased=False);
axes.set_zlim3d(-1, 1);
plot_surface(self, X, Y, Z, *args, **kwargs) method of matplotlib.axes.Axes3DSubplot instance
Create a surface plot.
By default it will be colored in shades of a solid color,
but it also supports color mapping by supplying the *cmap*
argument.
============= ================================================
Argument Description
============= ================================================
*X*, *Y*, *Z* Data values as 2D arrays
*rstride* Array row stride (step size)
*cstride* Array column stride (step size)
*color* Color of the surface patches
*cmap* A colormap for the surface patches.
*facecolors* Face colors for the individual patches
*norm* An instance of Normalize to map values to colors
*vmin* Minimum value to map
*vmax* Maximum value to map
*shade* Whether to shade the facecolors
from IPython.display import Image
import mayavi.mlab as mlab
mlab.points3d(a[:,0],a[:,1],a[:,2],a[:,2]);
mlab.show()
Image(r"mlab1.png")
Plots glyphs (like points) at the position of the supplied data.
**Function signatures**::
points3d(x, y, z...)
points3d(x, y, z, s, ...)
points3d(x, y, z, f, ...)
x, y and z are numpy arrays, or lists, all of the same shape, giving
the positions of the points.
If only 3 arrays x, y, z are given, all the points are drawn with the
same size and color.
In addition, you can pass a fourth array s of the same
shape as x, y, and z giving an associated scalar value for each
point, or a function f(x, y, z) returning the scalar value. This
scalar value can be used to modulate the color and the size of the
points.
dphi, dtheta = np.pi/250.0, np.pi/250.0
[phi,theta] = np.mgrid[0:np.pi+dphi*1.5:dphi,0:2*np.pi+dtheta*1.5:dtheta]
m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4;
r = np.sin(m0*phi)**m1 + np.cos(m2*phi)**m3 + np.sin(m4*theta)**m5 + np.cos(m6*theta)**m7
x = r*np.sin(phi)*np.cos(theta)
y = r*np.cos(phi)
z = r*np.sin(phi)*np.sin(theta)
s = mlab.mesh(x, y, z)
mlab.show()
Image(r"mlab2.png")
Plots a surface using grid-spaced data supplied as 2D arrays.
**Function signatures**::
mesh(x, y, z, ...)
x, y, z are 2D arrays, all of the same shape, giving the positions of
the vertices of the surface. The connectivity between these points is
implied by the connectivity on the arrays.
For simple structures (such as orthogonal grids) prefer the `surf`
function, as it will create more efficient data structures. For mesh
defined by triangles rather than regular implicit connectivity, see the
`triangular_mesh` function.
x, y, z = np.mgrid[-2:3, -2:3, -2:3]
r = np.sqrt(x ** 2 + y ** 2 + z ** 4)
u = y * np.sin(r) / (r + 0.001)
v = -x * np.sin(r) / (r + 0.001)
w = np.zeros_like(z)
src=mlab.quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=1)
mlab.show()
Image(r"mlab3.png")
import numpy as np
x, y, z = np.ogrid[-10:10:20j, -10:10:20j, -10:10:20j]
s = np.sin(x*y*z)/(x*y*z)
mlab.contour3d(s)
mlab.show()
Image(r"mlab4.png")
x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
u = np.sin(np.pi*x) * np.cos(np.pi*z)
v = -2*np.sin(np.pi*y) * np.cos(2*np.pi*z)
w = np.cos(np.pi*x)*np.sin(np.pi*z) + np.cos(np.pi*y)*np.sin(2*np.pi*z)
flow = mlab.flow(u, v, w, seed_scale=1,
seed_resolution=5,
integration_direction='both')
mlab.show()
Image(r"mlab5.png")
x, y = np.mgrid[-7.:7.05:0.1, -5.:5.05:0.05]
f=np.sin(x + y) + np.sin(2 * x - y) + np.cos(3 * x + 4 * y)
s=mlab.surf(x, y, f)
mlab.show()
Image(r"mlab6.png")
Ignore the below lines
from IPython.core.display import HTML
def css_styling():
styles = open(r'custom.css', 'r').read()
return HTML(styles)
css_styling()