I want to plot N planes (say 10) parallel to XZ axis and equidistant to each other using python. If possible it would be nice to select the number of planes from user. It will be like, if user gives "20" then 20 planes will be drawn in 3D. This is what I did.But I would like to know is there a method to call each plane or like to get each plane's equation ??
import numpy as np
import itertools
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
plt3d = plt.figure().gca(projection='3d')
xx, zz = np.meshgrid(range(10), range(10))
yy =0.5
for _ in itertools.repeat(None, 20):
plt3d.plot_surface(xx, yy, zz)
plt.hold(True)
yy=yy+.1
plt.show()
Here is an example how to implement what you need in a very generic way.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
from pylab import meshgrid,linspace,zeros,dot,norm,cross,vstack,array,matrix,sqrt
def rotmatrix(axis,costheta):
""" Calculate rotation matrix
Arguments:
- `axis` : Rotation axis
- `costheta` : Rotation angle
"""
x,y,z = axis
c = costheta
s = sqrt(1-c*c)
C = 1-c
return matrix([[ x*x*C+c, x*y*C-z*s, x*z*C+y*s ],
[ y*x*C+z*s, y*y*C+c, y*z*C-x*s ],
[ z*x*C-y*s, z*y*C+x*s, z*z*C+c ]])
def plane(Lx,Ly,Nx,Ny,n,d):
""" Calculate points of a generic plane
Arguments:
- `Lx` : Plane Length first direction
- `Ly` : Plane Length second direction
- `Nx` : Number of points, first direction
- `Ny` : Number of points, second direction
- `n` : Plane orientation, normal vector
- `d` : distance from the origin
"""
x = linspace(-Lx/2,Lx/2,Nx)
y = linspace(-Ly/2,Ly/2,Ny)
# Create the mesh grid, of a XY plane sitting on the orgin
X,Y = meshgrid(x,y)
Z = zeros([Nx,Ny])
n0 = array([0,0,1])
# Rotate plane to the given normal vector
if any(n0!=n):
costheta = dot(n0,n)/(norm(n0)*norm(n))
axis = cross(n0,n)/norm(cross(n0,n))
rotMatrix = rotmatrix(axis,costheta)
XYZ = vstack([X.flatten(),Y.flatten(),Z.flatten()])
X,Y,Z = array(rotMatrix*XYZ).reshape(3,Nx,Ny)
dVec = (n/norm(n))*d
X,Y,Z = X+dVec[0],Y+dVec[1],Z+dVec[2]
return X,Y,Z
if __name__ == "__main__":
# Plot as many planes as you like
Nplanes = 10
# Set color list from a cmap
colorList = cm.jet(linspace(0,1,Nplanes))
# List of Distances
distList = linspace(-10,10,Nplanes)
# Plane orientation - normal vector
normalVector = array([0,1,1]) # Y direction
# Create figure
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plotting
for i,ypos in enumerate(linspace(-10,10,10)):
# Calculate plane
X,Y,Z = plane(20,20,100,100,normalVector,distList[i])
ax.plot_surface(X, Y, Z, rstride=5, cstride=5,
alpha=0.8, color=colorList[i])
# Set plot display parameters
ax.set_xlabel('X')
ax.set_xlim(-10, 10)
ax.set_ylabel('Y')
ax.set_ylim(-10, 10)
ax.set_zlabel('Z')
ax.set_zlim(-10, 10)
plt.show()
If you need to rotate the plane around the normal vector, you can also use the rotation matrix for that.
Cheers
Related
Suppose I have a circle x**2 + y**2 = 20.
Now I want to plot the circle with n_dots number of dots in the circles perimeter in a scatter plot. So I created the code like below:
n_dots = 200
x1 = np.random.uniform(-20, 20, n_dots//2)
y1_1 = (400 - x1**2)**.5
y1_2 = -(400 - x1**2)**.5
plt.figure(figsize=(8, 8))
plt.scatter(x1, y1_1, c = 'blue')
plt.scatter(x1, y1_2, c = 'blue')
plt.show()
But this shows the dots not uniformly distributed all the places in the circle. The output is :
So how to create a circle with dots in scatter plot where all the dots are uniformly distributed in the perimeter of the circle?
A simple way to plot evenly-spaced points along the perimeter of a circle begins with dividing the whole circle into equally small angles where the angles from circle's center to all points are obtained. Then, the coordinates (x,y) of each point can be computed. Here is the code that does the task:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(figsize=(8, 8))
n_dots = 120 # set number of dots
angs = np.linspace(0, 2*np.pi, n_dots) # angles to the dots
cx, cy = (50, 20) # center of circle
xs, ys = [], [] # for coordinates of points to plot
ra = 20.0 # radius of circle
for ang in angs:
# compute (x,y) for each point
x = cx + ra*np.cos(ang)
y = cy + ra*np.sin(ang)
xs.append(x) # collect x
ys.append(y) # collect y
plt.scatter(xs, ys, c = 'red', s=5) # plot points
plt.show()
The resulting plot:
Alternately, numpy's broadcasting nature can be used and shortened the code:
import matplotlib.pyplot as plt
import numpy as np
fig=plt.figure(figsize=(8, 8))
n_dots = 120 # set number of dots
angs = np.linspace(0, 2*np.pi, n_dots) # angles to the dots
cx, cy = (50, 20) # center of circle
ra = 20.0 # radius of circle
# with numpy's broadcasting feature...
# no need to do loop computation as in above version
xs = cx + ra*np.cos(angs)
ys = cy + ra*np.sin(angs)
plt.scatter(xs, ys, c = 'red', s=5) # plot points
plt.show()
for a very generalized answer that also works in 2D:
import numpy as np
import matplotlib.pyplot as plt
def u_sphere_pts(dim, N):
"""
uniform distribution points on hypersphere
from uniform distribution in n-D (<-1, +1>) hypercube,
clipped by unit 2 norm to get the points inside the insphere,
normalize selected points to lie on surface of unit radius hypersphere
"""
# uniform points in hypercube
u_pts = np.random.uniform(low=-1.0, high=1.0, size=(dim, N))
# n dimensional 2 norm squared
norm2sq = (u_pts**2).sum(axis=0)
# mask of points where 2 norm squared < 1.0
in_mask = np.less(norm2sq, np.ones(N))
# use mask to select points, norms inside unit hypersphere
in_pts = np.compress(in_mask, u_pts, axis=1)
in_norm2 = np.sqrt(np.compress(in_mask, norm2sq)) # only sqrt selected
# return normalized points, equivalently, projected to hypersphere surface
return in_pts/in_norm2
# show some 2D "sphere" points
N = 1000
dim = 2
fig2, ax2 = plt.subplots()
ax2.scatter(*u_sphere_pts(dim, N))
ax2.set_aspect('equal')
plt.show()
# plot histogram of angles
pts = u_sphere_pts(dim, 1000000)
theta = np.arctan2(pts[0,:], pts[1,:])
num_bins = 360
fig1, ax1 = plt.subplots()
n, bins, patches = plt.hist(theta, num_bins, facecolor='blue', alpha=0.5)
plt.show()
similar/related:
https://stackoverflow.com/questions/45580865/python-generate-an-n-dimensional-hypercube-using-rejection-sampling#comment78122144_45580865
Python Uniform distribution of points on 4 dimensional sphere
http://mathworld.wolfram.com/HyperspherePointPicking.html
Sampling uniformly distributed random points inside a spherical volume
I would like to plot the surface of my data which is given by 3D vectors in cartesian coordinates x,y,z. The data can not be represented by a smooth function.
So first we generate some dummy data with the function eq_points(N_count, r) which returns an array points with the x,y,z coordinates of each point on the surface of our object. The quantity omega is the solid angle, and not of interest right now.
#credit to Markus Deserno from MPI
#https://www.cmu.edu/biolphys/deserno/pdf/sphere_equi.pdf
def eq_points(N_count, r):
points = []
a = 4*np.pi*r**2/N_count
d = np.sqrt(a)
M_theta = int(np.pi/d)
d_theta = np.pi/M_theta
d_phi = a/d_theta
for m in range(M_theta):
theta = np.pi*(m+0.5)/M_theta
M_phi = int(2*np.pi*np.sin(theta)/d_phi)
for n in range(M_phi):
phi = 2*np.pi*n/M_phi
points.append(np.array([r*np.sin(theta)*np.cos(phi),
r*np.sin(theta)*np.sin(phi),
r*np.cos(theta)]))
omega = 4*np.pi/N_count
return np.array(points), omega
#starting plotting sequence
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
points, omega = eq_points(400, 1.)
ax.scatter(points[:,0], points[:,1], points[:,2])
ax.scatter(0., 0., 0., c="r")
ax.set_xlabel(r'$x$ axis')
ax.set_ylabel(r'$y$ axis')
ax.set_zlabel(r'$Z$ axis')
plt.savefig("./sphere.png", format="png", dpi=300)
plt.clf()
The result is a sphere shown in the following figure. The blue points mark the data from the points array, while the red point is the origin.
I would like to get something like this
taken from here. However the data in the mplot3d tutorial is always a result of a smooth function. Except to the ax.scatter() function which I used for my sphere plot.
So in the end my goal would be to plot some data showing only its surface. This data is produced by changing the radial distance to the origin of each blue point. Further more it would be necessary to make sure each point is in contact with the surface. How are the surfaces which are plotted here e.g. in plot_surface() constructed in detail? Some actual live data looks like this:
I would suggest finding the hull, and then plotting the simplices (i.e. the triangles forming the hull). Make sure to update the x,y,z-limits appropriately.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import ConvexHull
N = 1000
pts = np.random.randn(N, 3)
# exclude outliers
# obviously, this is data dependent
cutoff = 3.
is_outlier = np.any(np.abs(pts) > cutoff, axis=1)
pts = pts[~is_outlier]
# plot points
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(pts[:,0], pts[:,1], pts[:,2])
ax.set_xlim(-(cutoff +1), cutoff+1)
ax.set_ylim(-(cutoff +1), cutoff+1)
ax.set_zlim(-(cutoff +1), cutoff+1)
# get and plot hull
hull = ConvexHull(pts)
fig = plt.figure()
ax = Axes3D(fig)
vertices = [pts[s] for s in hull.simplices]
triangles = Poly3DCollection(vertices, edgecolor='k')
ax.add_collection3d(triangles)
ax.set_xlim(-(cutoff +1), cutoff+1)
ax.set_ylim(-(cutoff +1), cutoff+1)
ax.set_zlim(-(cutoff +1), cutoff+1)
plt.show()
Solution to the question with the new specification that all points are touching the surface. Assuming that the angles are set by the user as shown in the example, it is easy to precompute the indices of the points forming the simplices making up the surface by computing the simplices of the hull formed by points on the unit sphere with the same angles as in the data set of interest. We can then use these indices to get the surface of interest.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
from scipy.spatial import ConvexHull
def eq_points(N_count, r):
points = []
a = 4*np.pi*r**2/N_count
d = np.sqrt(a)
M_theta = int(np.pi/d)
d_theta = np.pi/M_theta
d_phi = a/d_theta
for m in range(M_theta):
theta = np.pi*(m+0.5)/M_theta
M_phi = int(2*np.pi*np.sin(theta)/d_phi)
for n in range(M_phi):
phi = 2*np.pi*n/M_phi
points.append(np.array([r*np.sin(theta)*np.cos(phi),
r*np.sin(theta)*np.sin(phi),
r*np.cos(theta)]))
omega = 4*np.pi/N_count
return np.array(points), omega
def eq_points_with_random_radius(N_count, r):
points = []
a = 4*np.pi*r**2/N_count
d = np.sqrt(a)
M_theta = int(np.pi/d)
d_theta = np.pi/M_theta
d_phi = a/d_theta
for m in range(M_theta):
theta = np.pi*(m+0.5)/M_theta
M_phi = int(2*np.pi*np.sin(theta)/d_phi)
for n in range(M_phi):
phi = 2*np.pi*n/M_phi
rr = r * np.random.rand()
points.append(np.array([rr*np.sin(theta)*np.cos(phi),
rr*np.sin(theta)*np.sin(phi),
rr*np.cos(theta)]))
omega = 4*np.pi/N_count
return np.array(points), omega
N = 400
pts, _ = eq_points(N, 1.)
pts_rescaled, _ = eq_points_with_random_radius(N, 1.)
extremum = 2.
# plot points
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(pts_rescaled[:,0], pts_rescaled[:,1], pts_rescaled[:,2])
ax.set_xlim(-extremum, extremum)
ax.set_ylim(-extremum, extremum)
ax.set_zlim(-extremum, extremum)
# get indices of simplices making up the surface using points on unit sphere;
# index into rescaled points
hull = ConvexHull(pts)
vertices = [pts_rescaled[s] for s in hull.simplices]
fig = plt.figure()
ax = Axes3D(fig)
triangles = Poly3DCollection(vertices, edgecolor='k')
ax.add_collection3d(triangles)
ax.set_xlim(-extremum, extremum)
ax.set_ylim(-extremum, extremum)
ax.set_zlim(-extremum, extremum)
plt.show()
I have a 3d velocity vector field in a numpy array of shape (zlength, ylength, xlength, 3). The '3' contains the velocity components (u,v,w).
I can quite easily plot the vector field in the orthogonal x-y, x-z, and y-z planes using quiver, e.g.
X, Y = np.meshgrid(xvalues, yvalues)
xyfieldfig = plt.figure()
xyfieldax = xyfieldfig.add_subplot(111)
Q1 = xyfieldax.quiver(X, Y, velocity_field[zslice,:,:,0], velocity_field[zslice,:,:,1])
However, I'd like to be able to view the velocity field within an arbitrary plane.
I tried to project the velocity field onto a plane by doing:
projected_field = np.zeros(zlength,ylength,xlength,3)
normal = (nx,ny,nz) #normalised normal to the plane
for i in range(zlength):
for j in range(ylength):
for k in range(xlength):
projected_field[i,j,m] = velocity_field[i,j,m] - np.dot(velocity_field[i,j,m], normal)*normal
However, this (of course) still leaves me with a 3d numpy array with the same shape: (zlength, ylength, xlength, 3). The projected_field now contains velocity vectors at each (x,y,z) position that lie within planes at each local (x,y,z) position.
How do I project velocity_field onto a single plane? Or, how do I now plot my projected_field along one plane?
Thanks in advance!
You're close. Daniel F's suggestion was right, you just need to know how to do the interpolation. Here's a worked example
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate
def norm(v,axis=0):
return np.sqrt(np.sum(v**2,axis=axis))
#Original velocity field
xpoints = np.arange(-.2, .21, 0.05)
ypoints = np.arange(-.2, .21, 0.05)
zpoints = np.arange(-.2, .21, 0.05)
x, y, z = np.meshgrid(xpoints,ypoints,zpoints,indexing='ij')
#Simple example
#(u,v,w) are the components of your velocity field
u = x
v = y
w = z
#Setup a template for the projection plane. z-axis will be rotated to point
#along the plane normal
planex, planey, planez =
np.meshgrid(np.arange(-.2,.2001,.1),
np.arange(-.2,.2001,.1), [0.1],
indexing='ij')
planeNormal = np.array([0.1,0.4,.4])
planeNormal /= norm(planeNormal)
#pick an arbirtrary vector for projection x-axis
u0 = np.array([-(planeNormal[2] + planeNormal[1])/planeNormal[0], 1, 1])
u1 = -np.cross(planeNormal,u0)
u0 /= norm(u0)
u1 /= norm(u1)
#rotation matrix
rotation = np.array([u0,u1,planeNormal]).T
#Rotate plane to get projection vertices
rotatedVertices = rotation.dot( np.array( [planex.flatten(), planey.flatten(), planez.flatten()]) ).T
#Now you can interpolate gridded vector field to rotated vertices
uprime = scipy.interpolate.interpn( (xpoints,ypoints,zpoints), u, rotatedVertices, bounds_error=False )
vprime = scipy.interpolate.interpn( (xpoints,ypoints,zpoints), v, rotatedVertices, bounds_error=False )
wprime = scipy.interpolate.interpn( (xpoints,ypoints,zpoints), w, rotatedVertices, bounds_error=False )
#Projections
cosineMagnitudes = planeNormal.dot( np.array([uprime,vprime,wprime]) )
uProjected = uprime - planeNormal[0]*cosineMagnitudes
vProjected = vprime - planeNormal[1]*cosineMagnitudes
wProjected = wprime - planeNormal[2]*cosineMagnitudes
The number of lines could be reduced using some tensordot operations if you wanted to get fancy. Also this or some close variant it would work without indexing='ij' in meshgrid.
Original field:
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)
Projected field:
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.quiver(rotatedVertices[:,0], rotatedVertices[:,1], rotatedVertices[:,2],
uprime, vprime,wprime, length=0.5, color='blue', label='Interpolation only')
ax.quiver(rotatedVertices[:,0], rotatedVertices[:,1], rotatedVertices[:,2],
uProjected, vProjected, wProjected, length=0.5, color='red', label='Interpolation + Projection')
plt.legend()
I need to plot contour and quiver plots of scalar and vector fields defined on an uneven grid in (r,theta) coordinates.
As a minimal example of the problem I have, consider the contour plot of a Stream function for a magnetic dipole, contours of such a function are streamlines of the corresponeding vector field (in this case, the magnetic field).
The code below takes an uneven grid in (r,theta) coordinates, maps it to the cartesian plane and plots a contour plot of the stream function.
import numpy as np
import matplotlib.pyplot as plt
r = np.logspace(0,1,200)
theta = np.linspace(0,np.pi/2,100)
N_r = len(r)
N_theta = len(theta)
# Polar to cartesian coordinates
theta_matrix, r_matrix = np.meshgrid(theta, r)
x = r_matrix * np.cos(theta_matrix)
y = r_matrix * np.sin(theta_matrix)
m = 5
psi = np.zeros((N_r, N_theta))
# Stream function for a magnetic dipole
psi = m * np.sin(theta_matrix)**2 / r_matrix
contour_levels = m * np.sin(np.linspace(0, np.pi/2,40))**2.
fig, ax = plt.subplots()
# ax.plot(x,y,'b.') # plot grid points
ax.set_aspect('equal')
ax.contour(x, y, psi, 100, colors='black',levels=contour_levels)
plt.show()
For some reason though, the plot I get doesn't look right:
If I interchange x and y in the contour function call, I get the desired result:
Same thing happens when I try to make a quiver plot of a vector field defined on the same grid and mapped to the x-y plane, except that interchanging x and y in the function call no longer works.
It seems like I made a stupid mistake somewhere but I can't figure out what it is.
If psi = m * np.sin(theta_matrix)**2 / r_matrix
then psi increases as theta goes from 0 to pi/2 and psi decreases as r increases.
So a contour line for psi should increase in r as theta increases. That results
in a curve that goes counterclockwise as it radiates out from the center. This is
consistent with the first plot you posted, and the result returned by the first version of your code with
ax.contour(x, y, psi, 100, colors='black',levels=contour_levels)
An alternative way to confirm the plausibility of the result is to look at a surface plot of psi:
import numpy as np
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as axes3d
r = np.logspace(0,1,200)
theta = np.linspace(0,np.pi/2,100)
N_r = len(r)
N_theta = len(theta)
# Polar to cartesian coordinates
theta_matrix, r_matrix = np.meshgrid(theta, r)
x = r_matrix * np.cos(theta_matrix)
y = r_matrix * np.sin(theta_matrix)
m = 5
# Stream function for a magnetic dipole
psi = m * np.sin(theta_matrix)**2 / r_matrix
contour_levels = m * np.sin(np.linspace(0, np.pi/2,40))**2.
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.set_aspect('equal')
ax.plot_surface(x, y, psi, rstride=8, cstride=8, alpha=0.3)
ax.contour(x, y, psi, colors='black',levels=contour_levels)
plt.show()
I am trying to use python3 and matplotlib (version 1.4.0) to plot a scalar function defined on the surface of a sphere. I would like to have faces distributed relatively evenly over the sphere, so I am not using a meshgrid. This has led me to use plot_trisurf to plot my function. I have tested it with a trivial scalar function, and am having the problem that there are rendering artefacts along the edges of the faces:
The code I used to create the plot is below:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.tri as mtri
from scipy.spatial import ConvexHull
def points_on_sphere(N):
""" Generate N evenly distributed points on the unit sphere centered at
the origin. Uses the 'Golden Spiral'.
Code by Chris Colbert from the numpy-discussion list.
"""
phi = (1 + np.sqrt(5)) / 2 # the golden ratio
long_incr = 2*np.pi / phi # how much to increment the longitude
dz = 2.0 / float(N) # a unit sphere has diameter 2
bands = np.arange(N) # each band will have one point placed on it
z = bands * dz - 1 + (dz/2) # the height z of each band/point
r = np.sqrt(1 - z*z) # project onto xy-plane
az = bands * long_incr # azimuthal angle of point modulo 2 pi
x = r * np.cos(az)
y = r * np.sin(az)
return x, y, z
def average_g(triples):
return np.mean([triple[2] for triple in triples])
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = points_on_sphere(2**12)
Triples = np.array(list(zip(X, Y, Z)))
hull = ConvexHull(Triples)
triangles = hull.simplices
colors = np.array([average_g([Triples[idx] for idx in triangle]) for
triangle in triangles])
collec = ax.plot_trisurf(mtri.Triangulation(X, Y, triangles),
Z, shade=False, cmap=plt.get_cmap('Blues'), array=colors,
edgecolors='none')
collec.autoscale()
plt.show()
This problem appears to have been discussed in this question, but I can't seem to figure out how to set the edgecolors to match the facecolors. The two things I've tried are setting edgecolors='face' and calling collec.set_edgecolors() with a variety of arguments, but those throw AttributeError: 'Poly3DCollection' object has no attribute '_facecolors2d'.
How am I supposed to set the edgecolor equal to the facecolor in a trisurf plot?
You can set antialiased argument of plot_trisurf() to False. Here is the result: