Hướng dẫn 3d array python

There are many ways to address your problem.

  1. First one as accepted answer by @robert. Here is the generalised solution for it:
def multi_dimensional_list[value, *args]:
  #args dimensions as many you like. EG: [*args = 4,3,2 => x=4, y=3, z=2]
  #value can only be of immutable type. So, don't pass a list here. Acceptable value = 0, -1, 'X', etc.
  if len[args] > 1:
    return [ multi_dimensional_list[value, *args[1:]] for col in range[args[0]]]
  elif len[args] == 1: #base case of recursion
    return [ value for col in range[args[0]]]
  else: #edge case when no values of dimensions is specified.
    return None

Eg:

>>> multi_dimensional_list[-1, 3, 4]  #2D list
[[-1, -1, -1, -1], [-1, -1, -1, -1], [-1, -1, -1, -1]]
>>> multi_dimensional_list[-1, 4, 3, 2]  #3D list
[[[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]], [[-1, -1], [-1, -1], [-1, -1]]]
>>> multi_dimensional_list[-1, 2, 3, 2, 2 ]  #4D list
[[[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]], [[[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]], [[-1, -1], [-1, -1]]]]

P.S If you are keen to do validation for correct values for args i.e. only natural numbers, then you can write a wrapper function before calling this function.

  1. Secondly, any multidimensional dimensional array can be written as single dimension array. This means you don't need a multidimensional array. Here are the function for indexes conversion:
def convert_single_to_multi[value, max_dim]:
  dim_count = len[max_dim]
  values = [0]*dim_count
  for i in range[dim_count-1, -1, -1]: #reverse iteration
    values[i] = value%max_dim[i]
    value /= max_dim[i]
  return values


def convert_multi_to_single[values, max_dim]:
  dim_count = len[max_dim]
  value = 0
  length_of_dimension = 1
  for i in range[dim_count-1, -1, -1]: #reverse iteration
    value += values[i]*length_of_dimension
    length_of_dimension *= max_dim[i]
  return value

Since, these functions are inverse of each other, here is the output:

>>> convert_single_to_multi[convert_multi_to_single[[1,4,6,7],[23,45,32,14]],[23,45,32,14]]
[1, 4, 6, 7]
>>> convert_multi_to_single[convert_single_to_multi[21343,[23,45,32,14]],[23,45,32,14]]
21343
  1. If you are concerned about performance issues then you can use some libraries like pandas, numpy, etc.

I want to plot the result of a numerical method for a three dimensional system of ODEs. My output is in the form [let's suppose we have computed three steps]:

Nội dung chính

  • Three-dimensional Points and Lines¶
  • Three-dimensional Contour Plots¶
  • Wireframes and Surface Plots¶
  • Surface Triangulations¶
  • Example: Visualizing a Möbius strip¶
  • How do you plot a 3D NumPy array in Python?
  • Can you plot NumPy array?
  • How do you plot 3D data in Python?
  • How do you make a 3D array in Python?

import numpy as np
v= np.array[[[1,2,3], [4,5,6], [7,8,9]]]

Where the first value in every 3-tuple is the x coordinate, the second is y coordinate and the third is the z coordinate.

I would like the most simple and efficient way of plotting these points on a 3D grid. The problem seems to be that the data should be formated like np.array[[[1,4,7], [2,5,8], [3,6,9]]].

To create a 3D plot from a 3D numpy array, we can create a 3D array using numpy and extract the x, y, and z points.

  • Create a new figure or activate an existing figure using figure[] method.
  • Add an '~.axes.Axes' to the figure as part of a subplot arrangement using add_subplot[] method.
  • Create a random data of size=[3, 3, 3].
  • Extract x, y, and z data from the 3D array.
  • Plot 3D scattered points on the created axis
  • To display the figure, use show[] method.

Example

import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure[]
ax = fig.add_subplot[111, projection='3d']
data = np.random.random[size=[3, 3, 3]]
z, x, y = data.nonzero[]
ax.scatter[x, y, z, c=z, alpha=1]
plt.show[]

Output

Updated on 15-May-2021 12:02:05

  • Related Questions & Answers
  • How to surface plot/3D plot from a dataframe [Matplotlib]?
  • Creating 3D animation using matplotlib
  • How to display a 3D plot of a 3D array isosurface in matplotlib mplot3D or similar?
  • Saving a 3D-plot in a PDF 3D with Python
  • How to plot a 3D continuous line in Matplotlib?
  • How to plot a 3D patch collection in matplotlib?
  • Plot Matplotlib 3D plot_surface with contour plot projection
  • Plot 3D bars without axes in Matplotlib
  • Setting the aspect ratio of a 3D plot in Matplotlib
  • How to plot a point on 3D axes in Matplotlib?
  • Plot a 3D surface from {x,y,z}-scatter data in Python Matplotlib
  • How to plot a 3D density map in Python with Matplotlib?
  • How to plot 3D graphs using Python Matplotlib?
  • Animate a rotating 3D graph in Matplotlib
  • Plotting a 3D surface from a list of tuples in matplotlib?

Matplotlib was initially designed with only two-dimensional plotting in mind. Around the time of the 1.0 release, some three-dimensional plotting utilities were built on top of Matplotlib's two-dimensional display, and the result is a convenient [if somewhat limited] set of tools for three-dimensional data visualization. three-dimensional plots are enabled by importing the mplot3d toolkit, included with the main Matplotlib installation:

In [1]:

from mpl_toolkits import mplot3d

Once this submodule is imported, a three-dimensional axes can be created by passing the keyword projection='3d' to any of the normal axes creation routines:

In [2]:

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt

In [3]:

fig = plt.figure[]
ax = plt.axes[projection='3d']

With this three-dimensional axes enabled, we can now plot a variety of three-dimensional plot types. Three-dimensional plotting is one of the functionalities that benefits immensely from viewing figures interactively rather than statically in the notebook; recall that to use interactive figures, you can use %matplotlib notebook rather than %matplotlib inline when running this code.

Three-dimensional Points and Lines¶

The most basic three-dimensional plot is a line or collection of scatter plot created from sets of [x, y, z] triples. In analogy with the more common two-dimensional plots discussed earlier, these can be created using the ax.plot3D and ax.scatter3D functions. The call signature for these is nearly identical to that of their two-dimensional counterparts, so you can refer to Simple Line Plots and Simple Scatter Plots for more information on controlling the output. Here we'll plot a trigonometric spiral, along with some points drawn randomly near the line:

In [4]:

ax = plt.axes[projection='3d']

# Data for a three-dimensional line
zline = np.linspace[0, 15, 1000]
xline = np.sin[zline]
yline = np.cos[zline]
ax.plot3D[xline, yline, zline, 'gray']

# Data for three-dimensional scattered points
zdata = 15 * np.random.random[100]
xdata = np.sin[zdata] + 0.1 * np.random.randn[100]
ydata = np.cos[zdata] + 0.1 * np.random.randn[100]
ax.scatter3D[xdata, ydata, zdata, c=zdata, cmap='Greens'];

Notice that by default, the scatter points have their transparency adjusted to give a sense of depth on the page. While the three-dimensional effect is sometimes difficult to see within a static image, an interactive view can lead to some nice intuition about the layout of the points.

Three-dimensional Contour Plots¶

Analogous to the contour plots we explored in Density and Contour Plots, mplot3d contains tools to create three-dimensional relief plots using the same inputs. Like two-dimensional ax.contour plots, ax.contour3D requires all the input data to be in the form of two-dimensional regular grids, with the Z data evaluated at each point. Here we'll show a three-dimensional contour diagram of a three-dimensional sinusoidal function:

In [5]:

def f[x, y]:
    return np.sin[np.sqrt[x ** 2 + y ** 2]]

x = np.linspace[-6, 6, 30]
y = np.linspace[-6, 6, 30]

X, Y = np.meshgrid[x, y]
Z = f[X, Y]

In [6]:

fig = plt.figure[]
ax = plt.axes[projection='3d']
ax.contour3D[X, Y, Z, 50, cmap='binary']
ax.set_xlabel['x']
ax.set_ylabel['y']
ax.set_zlabel['z'];

Sometimes the default viewing angle is not optimal, in which case we can use the view_init method to set the elevation and azimuthal angles. In the following example, we'll use an elevation of 60 degrees [that is, 60 degrees above the x-y plane] and an azimuth of 35 degrees [that is, rotated 35 degrees counter-clockwise about the z-axis]:

Again, note that this type of rotation can be accomplished interactively by clicking and dragging when using one of Matplotlib's interactive backends.

Wireframes and Surface Plots¶

Two other types of three-dimensional plots that work on gridded data are wireframes and surface plots. These take a grid of values and project it onto the specified three-dimensional surface, and can make the resulting three-dimensional forms quite easy to visualize. Here's an example of using a wireframe:

In [8]:

fig = plt.figure[]
ax = plt.axes[projection='3d']
ax.plot_wireframe[X, Y, Z, color='black']
ax.set_title['wireframe'];

A surface plot is like a wireframe plot, but each face of the wireframe is a filled polygon. Adding a colormap to the filled polygons can aid perception of the topology of the surface being visualized:

In [9]:

ax = plt.axes[projection='3d']
ax.plot_surface[X, Y, Z, rstride=1, cstride=1,
                cmap='viridis', edgecolor='none']
ax.set_title['surface'];

Note that though the grid of values for a surface plot needs to be two-dimensional, it need not be rectilinear. Here is an example of creating a partial polar grid, which when used with the surface3D plot can give us a slice into the function we're visualizing:

In [10]:

r = np.linspace[0, 6, 20]
theta = np.linspace[-0.9 * np.pi, 0.8 * np.pi, 40]
r, theta = np.meshgrid[r, theta]

X = r * np.sin[theta]
Y = r * np.cos[theta]
Z = f[X, Y]

ax = plt.axes[projection='3d']
ax.plot_surface[X, Y, Z, rstride=1, cstride=1,
                cmap='viridis', edgecolor='none'];

Surface Triangulations¶

For some applications, the evenly sampled grids required by the above routines is overly restrictive and inconvenient. In these situations, the triangulation-based plots can be very useful. What if rather than an even draw from a Cartesian or a polar grid, we instead have a set of random draws?

In [11]:

theta = 2 * np.pi * np.random.random[1000]
r = 6 * np.random.random[1000]
x = np.ravel[r * np.sin[theta]]
y = np.ravel[r * np.cos[theta]]
z = f[x, y]

We could create a scatter plot of the points to get an idea of the surface we're sampling from:

In [12]:

ax = plt.axes[projection='3d']
ax.scatter[x, y, z, c=z, cmap='viridis', linewidth=0.5];

This leaves a lot to be desired. The function that will help us in this case is ax.plot_trisurf, which creates a surface by first finding a set of triangles formed between adjacent points [remember that x, y, and z here are one-dimensional arrays]:

In [13]:

ax = plt.axes[projection='3d']
ax.plot_trisurf[x, y, z,
                cmap='viridis', edgecolor='none'];

The result is certainly not as clean as when it is plotted with a grid, but the flexibility of such a triangulation allows for some really interesting three-dimensional plots. For example, it is actually possible to plot a three-dimensional Möbius strip using this, as we'll see next.

Example: Visualizing a Möbius strip¶

A Möbius strip is similar to a strip of paper glued into a loop with a half-twist. Topologically, it's quite interesting because despite appearances it has only a single side! Here we will visualize such an object using Matplotlib's three-dimensional tools. The key to creating the Möbius strip is to think about it's parametrization: it's a two-dimensional strip, so we need two intrinsic dimensions. Let's call them $\theta$, which ranges from $0$ to $2\pi$ around the loop, and $w$ which ranges from -1 to 1 across the width of the strip:

In [14]:

theta = np.linspace[0, 2 * np.pi, 30]
w = np.linspace[-0.25, 0.25, 8]
w, theta = np.meshgrid[w, theta]

Now from this parametrization, we must determine the [x, y, z] positions of the embedded strip.

Thinking about it, we might realize that there are two rotations happening: one is the position of the loop about its center [what we've called $\theta$], while the other is the twisting of the strip about its axis [we'll call this $\phi$]. For a Möbius strip, we must have the strip makes half a twist during a full loop, or $\Delta\phi = \Delta\theta/2$.

Now we use our recollection of trigonometry to derive the three-dimensional embedding. We'll define $r$, the distance of each point from the center, and use this to find the embedded $[x, y, z]$ coordinates:

In [16]:

# radius in x-y plane
r = 1 + w * np.cos[phi]

x = np.ravel[r * np.cos[theta]]
y = np.ravel[r * np.sin[theta]]
z = np.ravel[w * np.sin[phi]]

Finally, to plot the object, we must make sure the triangulation is correct. The best way to do this is to define the triangulation within the underlying parametrization, and then let Matplotlib project this triangulation into the three-dimensional space of the Möbius strip. This can be accomplished as follows:

In [17]:

# triangulate in the underlying parametrization
from matplotlib.tri import Triangulation
tri = Triangulation[np.ravel[w], np.ravel[theta]]

ax = plt.axes[projection='3d']
ax.plot_trisurf[x, y, z, triangles=tri.triangles,
                cmap='viridis', linewidths=0.2];

ax.set_xlim[-1, 1]; ax.set_ylim[-1, 1]; ax.set_zlim[-1, 1];

Combining all of these techniques, it is possible to create and display a wide variety of three-dimensional objects and patterns in Matplotlib.

How do you plot a 3D NumPy array in Python?

MatPlotLib with Python.

Create a new figure or activate an existing figure using figure[] method..

Add an '~. axes. ... .

Create a random data of size=[3, 3, 3]..

Extract x, y, and z data from the 3D array..

Plot 3D scattered points on the created axis..

To display the figure, use show[] method..

Can you plot NumPy array?

In Python, matplotlib is a plotting library. We can use it along with the NumPy library of Python also. NumPy stands for Numerical Python and it is used for working with arrays.

How do you plot 3D data in Python?

Plot a single point in a 3D space.

Step 1: Import the libraries. import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D. ... .

Step 2: Create figure and axes. fig = plt.figure[figsize=[4,4]] ax = fig.add_subplot[111, projection='3d'] ... .

Step 3: Plot the point..

How do you make a 3D array in Python?

In Python to initialize a 3-dimension array, we can easily use the np. array function for creating an array and once you will print the 'arr1' then the output will display a 3-dimensional array.

Chủ Đề