I would like to plot a 3D matrix - essentially a box of numbers, each labelled by an x, y, z triad of coordinates- by assigning a different colour to each of the x, y, z point, according to its magnitude (for example, bigger numbers in red and smaller numbers in blue).
I cannot plot sections of the matrix, I rather need to plot the whole matrix together.
If we call matrix3D my matrix, its elements are built this way:
matrix3D[x][y][z] = np.exp(-(x**2+y**2+z**2))
How can I obtain the desired plot?
EDIT: Using Mayavi2 Contour3D(), I have tried to write the following:
from mayavi import mlab
X = np.arange(0, n_x, 1)
Y = np.arange(0, n_z, 1)
Z = np.arange(0, n_z, 1)
X, Y, Z = np.meshgrid(X, Y, Z)
obj = mlab.contour3d(X, Y, Z, matrix3D, contours=4, transparent=True)
where n_x, n_y, n_z are the dimension of the 3 axes. How can I actually see and/or save the image now?
If you need to plot the whole thing I think you're best taking a look at mayavi. This will let you plot a volume and you should be able to get the results you need.
I know you said you need to plot the whole thing at once, but this might still be of some use. You can use countourf to plot like this:
import numpy as np
import matplotlib.pyplot as plt
matrix3D = np.empty((10, 10, 10))
x = np.arange(10)
y = np.arange(10)
z = np.arange(10)
matrix3D[x][y][z] = np.exp(-(x**2+y**2+z**2))
fig = plt.figure()
ax = fig.add_subplot(plt.subplot(1, 1, 1))
ax.contourf(x, y, matrix3D[:, :, 3])
plt.show()
This gives you a slice of the 3D matrix (in this example the 4th slice).
Related
I am trying to get a heatmap kind of color map with known values at points in plane which are spread non-uniformly (i.e., not uniform or not in grid form)
import numpy as np
x = np.random.rand(100)
y = np.random.rand(100)
z = np.random.rand(100)
Here, Using x, y and z, I want a plot showing intensity z[i] at point coordinates (x[i], y[i])
I tried using pcolor mesh of matplotlib as follows
import matplotlib.pyplot as plt
plt.figure()
plt.pcolormesh(x.reshape(10, 10), y.reshape(10, 10), z.reshape(10, 10))
plt.colorbar()
plt.show()
But this is giving the following error,
UserWarning: The input coordinates to pcolormesh are interpreted as cell centers, but are not monotonically increasing or decreasing. This may lead to incorrectly calculated cell edges, in which case, please supply explicit cell edges to pcolormesh.
I'd rather use a tricontourf
In [11]: x = np.random.rand(10000)
...: y = np.random.rand(10000)
...: z = np.random.rand(10000)+3*x+2*y
...: plt.tricontourf(x, y, z)
...: plt.colorbar()
...: plt.show()
I have a large set of measurements that I want to visualize in 4D using matplotlib in Python.
Currently, my variables are arranged in this way:
x = np.array(range(0, v1))
y = np.array(range(0, v2))
z = np.array(range(0, v3))
I have C which is a 3D array containing measurement values for each combination of the previous variables. So it has a dimension of v1*v2*v3.
Currently, I visualize my measurements using contourf function and I plot that for each z value. This results in 3D contour plot i.e. 2D + color map for the values. Now, I want to combine all the variables and look at the measurements in 4D dimensions (x, y, z, and color corresponding to the measurement value). What is the most efficient way to do this in python?
Regarding to #Sameeresque answer, I think the question was about a 4D graph like this (three coordinates x, y, z and a color as the fourth coordinate):
import numpy as np
import matplotlib.pyplot as plt
# only for example, use your grid
z = np.linspace(0, 1, 15)
x = np.linspace(0, 1, 15)
y = np.linspace(0, 1, 15)
X, Y, Z = np.meshgrid(x, y, z)
# Your 4dimension, only for example (use yours)
U = np.exp(-(X/2) ** 2 - (Y/3) ** 2 - Z ** 2)
# Creating figure
fig = plt.figure()
ax = plt.axes(projection="3d")
# Creating plot
ax.scatter3D(X, Y, Z, c=U, alpha=0.7, marker='.')
plt.show()
A 4D plot with (x,y,z) on the axis and the fourth being color can be obtained like so:
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = np.array(range(0, 50))
y = np.array(range(0, 50))
z = np.array(range(0, 50))
colors = np.random.standard_normal(len(x))
img = ax.scatter(x, y, z, c=colors, cmap=plt.hot())
fig.colorbar(img)
plt.show()
A simple way to visualize your 4D function, call it W(x, y, z), could be producing a gif of the cross-section contour plots along the z-axis.
Package plot4d could help you do it. An example plotting an isotropic 4D function:
from plot4d import plotter
import numpy as np
plotter.plot4d(lambda x,y,z:x**2+y**2+z**2, np.linspace(0,1,20), wbounds=(0,3), fps=5)
The code above generates this gif:
So, I've got three arrays of data, X, Y, and Z, each 225 numbers long. What I would like to do is to plot all three values at the same time on a surface plot. When I try to use
ax.plot_surface(X,Y,Z)
it tells me that Z needs to be a 2D array. I've looked it up and I've seen that it's possible to plot Z if it was a function of X and Y, but I need the first Z point to be associated with the first X and Y point etc. Is this possible in Python?
If your arrays are all 1-D, then I think what you want is
ax.plot_trisurf(X,Y,Z, triangles=tri.triangles, cmap=plt.cm.Spectral)
See more info at https://matplotlib.org/examples/mplot3d/trisurf3d_demo2.html
So, I've got three arrays of data, X, Y, and Z, each 225 numbers long. What I would like to do is to plot all three values at the same time on a surface plot.
So, from what i understood you want to plot a 3d surface plot.
But it seems you are only providing 3 1xn arrays. (in this case n == 255)
When plotting a surface plot, what you are doing in practice is getting each and every possible combination of a base (XY plane) and telling how high is a point Z on that given XY coordinates, hence Z is depicted as a function Z(i,j)
but I need the first Z point to be associated with the first X and Y point etc. Is this possible in Python?
Yes, but if you associate each Z point to the first X,Y and so on, you would only have the Z values for X==Y, which would be incomplete information for your surfaceplot!
A good (great) example of surface plot comes from matplotlib official docs
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
which results in:
What the code is actually doing:
Defining the input vectors X and Y (both range and interval)
Making a meshgrid out of those vectors (if unclear as to what a meshgrid is, print the output!)
Defining a function over the X,Y domain
Applying it to get Z
If you check, X,Y and Z are 2 dimensional arrays!
Hope it helps!
Since the complete simulation is to big to post it right here only the code to plot the spectrum is given (I think this is enough)
d = i.sum(axis=2)
pylab.figure(figsize=(15,15))
pylab = imshow(d)
plt.axis('tight')
pylab.show()
This spectrum is given in pixel. But I would like to have this in the units of length. I will hope you may give me some advices.
Do you mean that you want axis ticks to show your custom dimensions instead of the number of pixels in d? If yes, use the extent keyword of imshow:
import numpy
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
d = numpy.random.normal(size=(20, 40))
fig = plt.figure()
s = fig.add_subplot(1, 1, 1)
s.imshow(d, extent=(0, 1, 0, 0.5), interpolation='none')
fig.tight_layout()
fig.savefig('tt.png')
I'm guess a bit at what your problem is, so let's start by stating my interpretation/ You have some 2D data d that you plot using imshow and the units on the x and y axes are in the number of pixels. For example in the following we see the x axis labelled from 0 -> 10 for the number of data points:
import numpy as np
import matplotlib.pyplot as plt
# Generate a fake d
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X, Y = np.meshgrid(x, y)
d = np.sin(X**2 + Y**2)
plt.imshow(d)
If this correctly describes your issue, then the solution is to avoid using imshow, which is designed to plot images. Firstly this will help as imshow attemps to interpolate to give a smoother image (which may hide features in the spectrum) and second because it is an image, there is no meaningful x and y data so it doesn't plot it.
The best alternative would be to use plt.pcolormesh which generate a psuedocolor plot of a 2D array and takes as arguments X and Y, which are both 2D arrays of points to which the values of d correspond.
For example:
# Generate a fake d
x = np.linspace(-1, 1, 10)
y = np.linspace(-1, 1, 10)
X, Y = np.meshgrid(x, y)
d = np.sin(X**2 + Y**2)
plt.pcolormesh(X, Y, d)
Now the x and y values correspond to the values of X and Y.
I am trying to plot 2D field data using matplotlib. So basically I want something similar to this:
In my actual case I have data stored in a file on my harddrive. However for simplicity consider the function z = f(x, y). I want a smooth 2D plot where z is visualised using color. I managed the plotting with the following lines of code:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-1, 1, 21)
y = np.linspace(-1, 1, 21)
z = np.array([i*i+j*j for j in y for i in x])
X, Y = np.meshgrid(x, y)
Z = z.reshape(21, 21)
plt.pcolor(X, Y, Z)
plt.show()
However, the plot I obtain is very coarse. Is there a very simple way to smooth the plot? I know something similar is possible with surface plots, however, those are 3D. I could change the camera angle to obtain a 2D representation, but I am convinced there is an easier way. I also tried imshow but then I have to think in graphic coordinates where the origin is in the upper left corner.
Problem solved
I managed to solve my problem using:
plt.imshow(Z,origin='lower',interpolation='bilinear')
If you can't change your mesh granularity, then try to go with imshow, which will essentially plot any 2D matrix as an image, where the values of each matrix cell represent the color to make that pixel. Using your example values:
In [3]: x = y = np.linspace(-1, 1, 21)
In [4]: z = np.array([i*i+j*j for j in y for i in x])
In [5]: Z = z.reshape(21, 21)
In [7]: plt.imshow(Z, interpolation='bilinear')
Out[7]: <matplotlib.image.AxesImage at 0x7f4864277650>
In [8]: plt.show()
you can use contourf
plt.contourf(X, Y, Z)
EDIT:
For more levels (smoother colour transitions), you can use more levels (contours)
For example:
plt.contourf(X, Y, Z, 100)