Related
I have been trying to get a plot of vector lines going using the matplotlib library and I keep getting something like this:
Not sure what is happening since the code I'm running seems to follow the syntax for how to make a basic quiver plot. I've tried messing with the array type to see if that's the issue but no luck. Some points on the plot just don't seem to be getting any vector data.
import matplotlib.pyplot as plt
import numpy as np
X = np.arange(-2,2,.1)
Y = np.arange(-2,2,.1)
x,y = np.meshgrid(X,Y)
m1 =1
m2 =2
x1 =4/3
x2 =2/3
omega = 3/8
u = -(m1/(abs(x-x1))**3)*(x-x1)-(m2/(abs(x-x2))**3)*(x-x2)+ x*omega
v = -(m1/(abs(y))**3)*(y)-(m2/(abs(y))**3)*(y)+ y*omega
fig, ax = plt.subplots()
ax.quiver(x,y,u,v)
plt.show()
A nice way, I find, to have a look at your data is to normalise the vector field and colour it by intensity. You can always mask glyphs for which the intensity is too low by using a Numpy MaskedArray. Have a look below.
import matplotlib.colors as cl
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
import numpy as np
x, y = np.meshgrid(np.linspace(-2, 2, 41), np.linspace(-2, 2, 41))
m1, m2, x1, x2, omega = (1, 2, 4 / 3, 2 / 3, 3 / 8)
u = -(m1 / abs(x - x1) ** 3 * (x - x1) - m2 / abs(x - x2) ** 3 * (x - x2)
+ x * omega)
v = y * (omega - (m1 + m2) / abs(y) ** 3)
fig, (ax, bx) = plt.subplots(ncols=2, figsize=(20, 10))
ax.quiver(x, y, u, v, antialiased=True, scale=1e4, width=6e-3, headwidth=3,
headlength=4, headaxislength=3.5, pivot='tail',
edgecolors='xkcd:white', linewidths=1)
ax.set_aspect('equal')
w = np.sqrt(u ** 2 + v ** 2)
quiv = bx.quiver(x, y, u / w, v / w, w, antialiased=True, scale=3e1,
width=6e-3, headwidth=3, headlength=4, headaxislength=3.5,
pivot='tail', edgecolors='xkcd:white', linewidths=1,
norm=cl.LogNorm(vmin=1e-1, vmax=1e3))
bx.set_aspect('equal')
fig.colorbar(quiv, cax=fig.add_axes([0.93, 0.1, 0.02, 0.8]),
extend='both', ticks=tck.LogLocator(),
format=tck.LogFormatterSciNotation())
Some of the y values are close to 0 so that you get crazily large v values. I would check the equation because the plot is actually correct (the arrows are infinitely large when y ~= 0).
I want to plot a quantity which is given on a parametric surface in 3d space (for example the temperature distribution on a sphere). I can plot a parametric 3D plot of the sphere (as a function of the two parameters phi and theta) but I don't know how to make the colors of the polygons making up the sphere depend on the parameters theta and phi (normally, the color of a polygon is simply determined by the z-Position of the polygon).
Here's a basic example which plots a torus with colormap:
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
angle = np.linspace(0, 2 * np.pi, 32)
theta, phi = np.meshgrid(angle, angle)
r, R = .25, 1.
X = (R + r * np.cos(phi)) * np.cos(theta)
Y = (R + r * np.cos(phi)) * np.sin(theta)
Z = r * np.sin(phi)
# Display the mesh
fig = plt.figure()
ax = fig.gca(projection = '3d')
ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(-1, 1)
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1,cmap="hot")
plt.show()
However, the colors of the files are given by the z position of the tile, I want the color to be given by a function f(x,y).
Does anyone know how I can achieve this dependency in Matplotlib?
Thanks very much!
Ok, if anyone else is looking for a solution to this problem here's a possible solution:
The colors of the individual faces making up the surface plot can be set using the keyword argument facecolors. The following code will use the function X**2+Y**2 for coloring the faces of the parametric surface:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.colors as mcolors
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
# Generate torus mesh
angle = np.linspace(0, 2 * np.pi, 32)
theta, phi = np.meshgrid(angle, angle)
r, R = .25, 1.
X = (R + r * np.cos(phi)) * np.cos(theta)
Y = (R + r * np.cos(phi)) * np.sin(theta)
Z = r * np.sin(phi)
colorfunction=(X**2+Y**2)
norm=mcolors.Normalize(colorfunction.min(),colorfunction.max())
# Display the mesh
fig = plt.figure(figsize=(7, 7))
ax = fig.add_subplot(projection='3d')
ax.set_xlim3d(-1, 1)
ax.set_ylim3d(-1, 1)
ax.set_zlim3d(-1, 1)
ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, facecolors=cm.jet(norm(colorfunction)))
plt.show()
[TLDR]:
Essentially my question boils down to how one can extract the 2d data of a plane from a 3D numpy meshgrid
[Detailed Description]:
I am calculating the electric field of two (or more) point charges. I did this in 2D and can plot the results via matplotlib using quiver or streamplot
import numpy as np
from matplotlib import pyplot as plt
eps_0 = 8e-12
fac = (1./(4*np.pi*eps_0))
charges = [1.0,-1.0]
qx = [-2.0,2.0]
qy = [0.0,0.0]
# GRID
gridsize = 4.0
N = 11
X,Y = np.meshgrid( np.linspace(-gridsize,gridsize,N),
np.linspace(-gridsize,gridsize,N))
# CALC E-FIELD
sumEx = np.zeros_like(X)
sumEy = np.zeros_like(Y)
for q, qxi, qyi in zip(charges,qx,qy):
dist_vec_x = X - qxi
dist_vec_y = Y - qyi
dist = np.sqrt(dist_vec_x**2 + dist_vec_y**2)
Ex = fac * q * (dist_vec_x/dist**3)
Ey = fac * q * (dist_vec_y/dist**3)
sumEx += Ex
sumEy += Ey
# PLOT
fig = plt.figure()
ax = fig.add_subplot(111)
ax.streamplot(X,Y,sumEx,sumEy)
plt.show()
This produces the correct results
I can easily extend this to 3D
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
eps_0 = 8e-12
fac = (1./(4*np.pi*eps_0))
charges = [1.0,-1.0]
qx = [-2.0,2.0]
qy = [0.0,0.0]
qz = [0.0,0.0]
# GRID
gridsize = 4.0
N = 11
X,Y,Z = np.meshgrid( np.linspace(-gridsize,gridsize,N),
np.linspace(-gridsize,gridsize,N),
np.linspace(-gridsize,gridsize,N))
# CALC E-FIELD
sumEx = np.zeros_like(X)
sumEy = np.zeros_like(Y)
sumEz = np.zeros_like(Z)
for q, qxi, qyi, qzi in zip(charges,qx,qy,qz):
dist_vec_x = X - qxi
dist_vec_y = Y - qyi
dist_vec_z = Z - qzi
dist = np.sqrt(dist_vec_x**2 + dist_vec_y**2 + dist_vec_z**2)
Ex = fac * q * (dist_vec_x/dist**3)
Ey = fac * q * (dist_vec_y/dist**3)
Ez = fac * q * (dist_vec_z/dist**3)
sumEx += Ex
sumEy += Ey
sumEz += Ez
# PLOT
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.quiver(X,Y,Z,sumEx,sumEy,sumEz, pivot='middle', normalize=True)
plt.show()
This also yields the correct result when plotted in 3D (as far as I can tell)
But for some reason I can not figure out how to extract the data from one x-y plane from the generated 3D numpy mesh. I thought I could just do something like
zplane = round(N/2)
ax.quiver(X,Y,sumEx[:,:,zplane],sumEy[:,:,zplane])
but this does not do the trick. Does anyone know the proper way here?
Remove projection='3d' and index X and Y:
fig = plt.figure()
ax = fig.gca()
zplane = round(N / 2)
ax.quiver(X[:, :, zplane], Y[:, :, zplane], sumEx[:, :, zplane], sumEy[:, :, zplane])
plt.show()
If you select a specific zplane your plot is no longer a 3D-plot.
I have irregularly spaced mesh points data in the form [[xi1,yi1,zi1], [xi2,yi2,zi2],....]. They form a part of a sphere
I also have data [[x1,y1,z1,n1],[x2,y2,z2,n2]....] where (x1,y1,z1) etc tells the coordinate of the midpoint of each mesh bin and ni are the densities at the corresponding locations. The 3d scatter plot with square markers of the data look like this (where the colors show the value of n)
its side view showing the curvature
I am trying to make this into a smooth surface plot. I have looked into this example matplotlib color but here the gridpoints are equally spaced while in my case they are not, also how would one represent the densities using color in such an irregular grid. I am open to trying other packages other than matplotlib.
Thanks
One method is to manually create and plot a collection of triangles:
(Edit: manually creating and coloring triangles around bin midpoints)
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.tri import Triangulation
from mpl_toolkits.mplot3d.art3d import Poly3DCollection
import matplotlib.cm as cm
# Generate a dataset
R = 1
# bin midpoints
theta = numpy.linspace(numpy.pi/6, numpy.pi/3, 20) + numpy.pi / 2
phi = numpy.linspace(numpy.pi/6, numpy.pi/3, 20)
ttheta, pphi = numpy.meshgrid(theta, phi)
x = R * numpy.sin(ttheta) * numpy.cos(pphi)
y = R * numpy.sin(ttheta) * numpy.sin(pphi)
z = R * numpy.cos(ttheta)
n = numpy.exp(-(ttheta - numpy.pi/4 - numpy.pi/2)**2 * 20 - (pphi - numpy.pi/4)**2 * 20)
mappable = cm.ScalarMappable(cmap=cm.coolwarm, norm=matplotlib.colors.Normalize(vmin=0, vmax=1))
colors = mappable.to_rgba(n)
# Scatter plot
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.scatter(x.flatten(), y.flatten(), z.flatten(), c=colors.reshape(x.size, 4))
ax.set_xlim(0.2, 0.8)
ax.set_ylim(0.2, 0.8)
ax.set_zlim(-0.9, -0.45)
ax.elev = 50
fig.savefig('t.png')
# Surface plot
# bin vertex spherical coordinates
dtheta = theta[1] - theta[0]
dphi = phi[1] - phi[0]
v_theta = numpy.concatenate([theta - dtheta/2, numpy.array([theta[-1] + dtheta/2])])
v_phi = numpy.concatenate([phi - dphi/2, numpy.array([phi[-1] + dphi/2])])
# bin vertex Cartesian coordinates
v_ttheta, v_pphi = numpy.meshgrid(v_theta, v_phi)
vx = R * numpy.sin(v_ttheta) * numpy.cos(v_pphi)
vy = R * numpy.sin(v_ttheta) * numpy.sin(v_pphi)
vz = R * numpy.cos(v_ttheta)
# Creating triangles and corresponding face colors
triangles = []
facecolors = []
for i in range(v_theta.size - 1):
for j in range(v_phi.size - 1):
triangles.extend([
[(i, j), (i + 1, j), (i, j + 1)],
[(i + 1, j), (i + 1, j + 1), (i, j + 1)]])
facecolors.extend([
colors[i, j],
colors[i, j]
])
triangle_vertices = numpy.array(
[[[vx[i,j], vy[i,j], vz[i,j]] for i, j in t] for t in triangles])
coll = Poly3DCollection(triangle_vertices, facecolors=facecolors, edgecolors=(0,0,0,0))
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1, projection='3d')
ax.add_collection(coll)
ax.set_xlim(0.2, 0.8)
ax.set_ylim(0.2, 0.8)
ax.set_zlim(-0.9, -0.45)
ax.elev = 50
fig.savefig('t2.png')
The scatter plot:
The surface plot:
I have the following problem:
a have N points on a sphere specified by a array x, with x.shape=(N,3). This array contains their cartesian coordinates. Furthermore, at each point, I have a specified temperature. This quantity is saved in an array T, with T.shape=(N,).
Is there any straight forward way to map this temperature distribution into the plane using different colors?
If it simplifies the task, the position can also be given in polar coordinates (\theta,\phi).
To plot your data, you can use Basemap. The only problem is, that both contour and contourf routines needs gridded data. Here is example with naive (and slow) IDW-like interpolation on sphere. Any comments are welcome.
import numpy as np
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
def cart2sph(x, y, z):
dxy = np.sqrt(x**2 + y**2)
r = np.sqrt(dxy**2 + z**2)
theta = np.arctan2(y, x)
phi = np.arctan2(z, dxy)
theta, phi = np.rad2deg([theta, phi])
return theta % 360, phi, r
def sph2cart(theta, phi, r=1):
theta, phi = np.deg2rad([theta, phi])
z = r * np.sin(phi)
rcosphi = r * np.cos(phi)
x = rcosphi * np.cos(theta)
y = rcosphi * np.sin(theta)
return x, y, z
# random data
pts = 1 - 2 * np.random.rand(500, 3)
l = np.sqrt(np.sum(pts**2, axis=1))
pts = pts / l[:, np.newaxis]
T = 150 * np.random.rand(500)
# naive IDW-like interpolation on regular grid
theta, phi, r = cart2sph(*pts.T)
nrows, ncols = (90,180)
lon, lat = np.meshgrid(np.linspace(0,360,ncols), np.linspace(-90,90,nrows))
xg,yg,zg = sph2cart(lon,lat)
Ti = np.zeros_like(lon)
for r in range(nrows):
for c in range(ncols):
v = np.array([xg[r,c], yg[r,c], zg[r,c]])
angs = np.arccos(np.dot(pts, v))
idx = np.where(angs == 0)[0]
if idx.any():
Ti[r,c] = T[idx[0]]
else:
idw = 1 / angs**2 / sum(1 / angs**2)
Ti[r,c] = np.sum(T * idw)
# set up map projection
map = Basemap(projection='ortho', lat_0=45, lon_0=15)
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))
# compute native map projection coordinates of lat/lon grid.
x, y = map(lon, lat)
# contour data over the map.
cs = map.contourf(x, y, Ti, 15)
plt.title('Contours of T')
plt.show()
One way to do this is to set facecolors by mapping your heat data through the colormap.
Here's an example:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
u = np.linspace(0, 2 * np.pi, 80)
v = np.linspace(0, np.pi, 80)
# create the sphere surface
x=10 * np.outer(np.cos(u), np.sin(v))
y=10 * np.outer(np.sin(u), np.sin(v))
z=10 * np.outer(np.ones(np.size(u)), np.cos(v))
# simulate heat pattern (striped)
myheatmap = np.abs(np.sin(y))
ax.plot_surface(x, y, z, cstride=1, rstride=1, facecolors=cm.hot(myheatmap))
plt.show()
Here, my "heatmap" is just stripes along the y-axis, which I made using the function np.abs(np.sin(y)), but anything that goes form 0 to 1 will work (and, of course, it needs to match the shapes on x, etc.