matplotlib & pandas

This commit is contained in:
estomm
2020-09-26 22:03:11 +08:00
parent 73cc328c81
commit d31be4f219
599 changed files with 99925 additions and 0 deletions

View File

@@ -0,0 +1,56 @@
# 在3D绘图上绘制2D数据
演示使用ax.plot的zdir关键字在3D绘图的选择轴上绘制2D数据。
![在3D绘图上绘制2D数据示例](https://matplotlib.org/_images/sphx_glr_2dcollections3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
# Plot a sin curve using the x and y axes.
x = np.linspace(0, 1, 100)
y = np.sin(x * 2 * np.pi) / 2 + 0.5
ax.plot(x, y, zs=0, zdir='z', label='curve in (x,y)')
# Plot scatterplot data (20 2D points per colour) on the x and z axes.
colors = ('r', 'g', 'b', 'k')
# Fixing random state for reproducibility
np.random.seed(19680801)
x = np.random.sample(20 * len(colors))
y = np.random.sample(20 * len(colors))
c_list = []
for c in colors:
c_list.extend([c] * 20)
# By using zdir='y', the y value of these points is fixed to the zs value 0
# and the (x,y) points are plotted on the x and z axes.
ax.scatter(x, y, zs=0, zdir='y', c=c_list, label='points in (x,z)')
# Make legend, set axes limits and labels
ax.legend()
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_zlim(0, 1)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# Customize the view angle so it's easier to see that the scatter points lie
# on the plane y=0
ax.view_init(elev=20., azim=-35)
plt.show()
```
## 下载这个示例
- [下载python源码: 2dcollections3d.py](https://matplotlib.org/_downloads/2dcollections3d.py)
- [下载Jupyter notebook: 2dcollections3d.ipynb](https://matplotlib.org/_downloads/2dcollections3d.ipynb)

View File

@@ -0,0 +1,41 @@
# 3D条形图演示
有关如何使用和不使用着色绘制3D条形图的基本演示。
![3D条形图演示](https://matplotlib.org/_images/sphx_glr_3d_bars_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
# setup the figure and axes
fig = plt.figure(figsize=(8, 3))
ax1 = fig.add_subplot(121, projection='3d')
ax2 = fig.add_subplot(122, projection='3d')
# fake data
_x = np.arange(4)
_y = np.arange(5)
_xx, _yy = np.meshgrid(_x, _y)
x, y = _xx.ravel(), _yy.ravel()
top = x + y
bottom = np.zeros_like(top)
width = depth = 1
ax1.bar3d(x, y, bottom, width, depth, top, shade=True)
ax1.set_title('Shaded')
ax2.bar3d(x, y, bottom, width, depth, top, shade=False)
ax2.set_title('Not Shaded')
plt.show()
```
## 下载这个示例
- [下载python源码: 3d_bars.py](https://matplotlib.org/_downloads/3d_bars.py)
- [下载Jupyter notebook: 3d_bars.ipynb](https://matplotlib.org/_downloads/3d_bars.ipynb)

View File

@@ -0,0 +1,49 @@
# 在不同的平面中创建二维条形图
演示制作3D绘图其中2D条形图投影到平面y = 0y = 1等。
![在不同的平面中创建二维条形图示例](https://matplotlib.org/_images/sphx_glr_bars3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
colors = ['r', 'g', 'b', 'y']
yticks = [3, 2, 1, 0]
for c, k in zip(colors, yticks):
# Generate the random data for the y=k 'layer'.
xs = np.arange(20)
ys = np.random.rand(20)
# You can provide either a single color or an array with the same length as
# xs and ys. To demonstrate this, we color the first bar of each set cyan.
cs = [c] * len(xs)
cs[0] = 'c'
# Plot the bar graph given by xs and ys on the plane y=k with 80% opacity.
ax.bar(xs, ys, zs=k, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
# On the y axis let's only label the discrete values that we have data for.
ax.set_yticks(yticks)
plt.show()
```
## 下载这个示例
- [下载python源码: bars3d.py](https://matplotlib.org/_downloads/bars3d.py)
- [下载Jupyter notebook: bars3d.ipynb](https://matplotlib.org/_downloads/bars3d.ipynb)

View File

@@ -0,0 +1,27 @@
# 演示在3D中绘制轮廓水平曲线
这类似于2D中的等高线图除了fxy= c曲线绘制在平面z = c上。
![演示在3D中绘制轮廓水平曲线示例](https://matplotlib.org/_images/sphx_glr_contour3d_001.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot contour curves
cset = ax.contour(X, Y, Z, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
```
## 下载这个示例
- [下载python源码: contour3d.py](https://matplotlib.org/_downloads/contour3d.py)
- [下载Jupyter notebook: contour3d.ipynb](https://matplotlib.org/_downloads/contour3d.ipynb)

View File

@@ -0,0 +1,26 @@
# 演示使用extend3d选项在3D中绘制轮廓水平曲线
contour3d_demo示例的这种修改使用extend3d = True将曲线垂直扩展为“ribbon”。
![演示使用extend3d选项在3D中绘制轮廓水平曲线示例](https://matplotlib.org/_images/sphx_glr_contour3d_2_001.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contour(X, Y, Z, extend3d=True, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
```
## 下载这个示例
- [下载python源码: contour3d_2.py](https://matplotlib.org/_downloads/contour3d_2.py)
- [下载Jupyter notebook: contour3d_2.ipynb](https://matplotlib.org/_downloads/contour3d_2.ipynb)

View File

@@ -0,0 +1,42 @@
# 将轮廓轮廓投影到图形上
演示显示3D表面同时还将轮廓“轮廓”投影到图形的“墙壁”上。
有关填充版本请参见contourf3d_demo2。
![将轮廓轮廓投影到图形上](https://matplotlib.org/_images/sphx_glr_contour3d_3_001.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
# Plot projections of the contours for each dimension. By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph
cset = ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax.set_xlim(-40, 40)
ax.set_ylim(-40, 40)
ax.set_zlim(-100, 100)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
```
## 下载这个示例
- [下载python源码: contour3d_3.py](https://matplotlib.org/_downloads/contour3d_3.py)
- [下载Jupyter notebook: contour3d_3.ipynb](https://matplotlib.org/_downloads/contour3d_3.ipynb)

View File

@@ -0,0 +1,28 @@
# 填充轮廓
contourf与轮廓的不同之处在于它创建了填充轮廓即。 离散数量的颜色用于遮蔽域。
这类似于2D中的等高线图除了对应于等级c的阴影区域在平面z = c上绘制图形。
![填充轮廓示例](https://matplotlib.org/_images/sphx_glr_contourf3d_001.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
cset = ax.contourf(X, Y, Z, cmap=cm.coolwarm)
ax.clabel(cset, fontsize=9, inline=1)
plt.show()
```
## 下载这个示例
- [下载python源码: contourf3d.py](https://matplotlib.org/_downloads/contourf3d.py)
- [下载Jupyter notebook: contourf3d.ipynb](https://matplotlib.org/_downloads/contourf3d.ipynb)

View File

@@ -0,0 +1,42 @@
# 将填充轮廓投影到图形上
演示显示3D表面同时还将填充的轮廓“轮廓”投影到图形的“墙壁”上。
有关未填充的版本请参见contour3d_demo2。
![将填充轮廓投影到图形上](https://matplotlib.org/_images/sphx_glr_contourf3d_2_0011.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax = fig.gca(projection='3d')
X, Y, Z = axes3d.get_test_data(0.05)
# Plot the 3D surface
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
# Plot projections of the contours for each dimension. By choosing offsets
# that match the appropriate axes limits, the projected contours will sit on
# the 'walls' of the graph
cset = ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm)
cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
ax.set_xlim(-40, 40)
ax.set_ylim(-40, 40)
ax.set_zlim(-100, 100)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()
```
## 下载这个示例
- [下载python源码: contourf3d_2.py](https://matplotlib.org/_downloads/contourf3d_2.py)
- [下载Jupyter notebook: contourf3d_2.ipynb](https://matplotlib.org/_downloads/contourf3d_2.ipynb)

View File

@@ -0,0 +1,45 @@
# 3D表面图中的自定义山体的阴影
演示在3D曲面图中使用自定义山体阴影。
![3D表面图中的自定义山体的阴影示例](https://matplotlib.org/_images/sphx_glr_custom_shaded_3d_surface_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
from matplotlib import cbook
from matplotlib import cm
from matplotlib.colors import LightSource
import matplotlib.pyplot as plt
import numpy as np
# Load and format data
filename = cbook.get_sample_data('jacksboro_fault_dem.npz', asfileobj=False)
with np.load(filename) as dem:
z = dem['elevation']
nrows, ncols = z.shape
x = np.linspace(dem['xmin'], dem['xmax'], ncols)
y = np.linspace(dem['ymin'], dem['ymax'], nrows)
x, y = np.meshgrid(x, y)
region = np.s_[5:50, 5:50]
x, y, z = x[region], y[region], z[region]
# Set up plot
fig, ax = plt.subplots(subplot_kw=dict(projection='3d'))
ls = LightSource(270, 45)
# To use a custom hillshading mode, override the built-in shading and pass
# in the rgb colors of the shaded surface calculated from "shade".
rgb = ls.shade(z, cmap=cm.gist_earth, vert_exag=0.1, blend_mode='soft')
surf = ax.plot_surface(x, y, z, rstride=1, cstride=1, facecolors=rgb,
linewidth=0, antialiased=False, shade=False)
plt.show()
```
## 下载这个示例
- [下载python源码: custom_shaded_3d_surface.py](https://matplotlib.org/_downloads/custom_shaded_3d_surface.py)
- [下载Jupyter notebook: custom_shaded_3d_surface.ipynb](https://matplotlib.org/_downloads/custom_shaded_3d_surface.ipynb)

View File

@@ -0,0 +1,41 @@
# 创建2D数据的3D直方图
将二维数据的直方图演示为3D中的条形图。
![创建2D数据的3D直方图示例](https://matplotlib.org/_images/sphx_glr_hist3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x, y = np.random.rand(2, 100) * 4
hist, xedges, yedges = np.histogram2d(x, y, bins=4, range=[[0, 4], [0, 4]])
# Construct arrays for the anchor positions of the 16 bars.
xpos, ypos = np.meshgrid(xedges[:-1] + 0.25, yedges[:-1] + 0.25, indexing="ij")
xpos = xpos.ravel()
ypos = ypos.ravel()
zpos = 0
# Construct arrays with the dimensions for the 16 bars.
dx = dy = 0.5 * np.ones_like(zpos)
dz = hist.ravel()
ax.bar3d(xpos, ypos, zpos, dx, dy, dz, color='b', zsort='average')
plt.show()
```
## 下载这个示例
- [下载python源码: hist3d.py](https://matplotlib.org/_downloads/hist3d.py)
- [下载Jupyter notebook: hist3d.ipynb](https://matplotlib.org/_downloads/hist3d.ipynb)

View File

@@ -0,0 +1,36 @@
# 参数曲线
此示例演示了如何在3D中绘制参数曲线。
![参数曲线示例](https://matplotlib.org/_images/sphx_glr_lines3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['legend.fontsize'] = 10
fig = plt.figure()
ax = fig.gca(projection='3d')
# Prepare arrays x, y, z
theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)
z = np.linspace(-2, 2, 100)
r = z**2 + 1
x = r * np.sin(theta)
y = r * np.cos(theta)
ax.plot(x, y, z, label='parametric curve')
ax.legend()
plt.show()
```
## 下载这个示例
- [下载python源码: lines3d.py](https://matplotlib.org/_downloads/lines3d.py)
- [下载Jupyter notebook: lines3d.ipynb](https://matplotlib.org/_downloads/lines3d.ipynb)

View File

@@ -0,0 +1,67 @@
# 洛伦兹吸引力
这是使用mplot3d在3维空间中绘制Edward Lorenz 1963年的[“确定性非周期流”](http://journals.ametsoc.org/doi/abs/10.1175/1520-0469%281963%29020%3C0130%3ADNF%3E2.0.CO%3B2)的示例。
注意因为这是一个简单的非线性ODE使用SciPy的ode求解器会更容易完成但这种方法仅取决于NumPy。
![洛伦兹吸引力示例](https://matplotlib.org/_images/sphx_glr_lorenz_attractor_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
def lorenz(x, y, z, s=10, r=28, b=2.667):
'''
Given:
x, y, z: a point of interest in three dimensional space
s, r, b: parameters defining the lorenz attractor
Returns:
x_dot, y_dot, z_dot: values of the lorenz attractor's partial
derivatives at the point x, y, z
'''
x_dot = s*(y - x)
y_dot = r*x - y - x*z
z_dot = x*y - b*z
return x_dot, y_dot, z_dot
dt = 0.01
num_steps = 10000
# Need one more for the initial values
xs = np.empty((num_steps + 1,))
ys = np.empty((num_steps + 1,))
zs = np.empty((num_steps + 1,))
# Set initial values
xs[0], ys[0], zs[0] = (0., 1., 1.05)
# Step through "time", calculating the partial derivatives at the current point
# and using them to estimate the next point
for i in range(num_steps):
x_dot, y_dot, z_dot = lorenz(xs[i], ys[i], zs[i])
xs[i + 1] = xs[i] + (x_dot * dt)
ys[i + 1] = ys[i] + (y_dot * dt)
zs[i + 1] = zs[i] + (z_dot * dt)
# Plot
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot(xs, ys, zs, lw=0.5)
ax.set_xlabel("X Axis")
ax.set_ylabel("Y Axis")
ax.set_zlabel("Z Axis")
ax.set_title("Lorenz Attractor")
plt.show()
```
## 下载这个示例
- [下载python源码: lorenz_attractor.py](https://matplotlib.org/_downloads/lorenz_attractor.py)
- [下载Jupyter notebook: lorenz_attractor.ipynb](https://matplotlib.org/_downloads/lorenz_attractor.ipynb)

View File

@@ -0,0 +1,56 @@
# 相同图中的2D和3D轴
此示例显示如何在同一图上绘制2D和3D绘图。
![相同图中的2D和3D轴示例](https://matplotlib.org/_images/sphx_glr_mixed_subplots_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
def f(t):
s1 = np.cos(2*np.pi*t)
e1 = np.exp(-t)
return np.multiply(s1, e1)
# Set up a figure twice as tall as it is wide
fig = plt.figure(figsize=plt.figaspect(2.))
fig.suptitle('A tale of 2 subplots')
# First subplot
ax = fig.add_subplot(2, 1, 1)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
t3 = np.arange(0.0, 2.0, 0.01)
ax.plot(t1, f(t1), 'bo',
t2, f(t2), 'k--', markerfacecolor='green')
ax.grid(True)
ax.set_ylabel('Damped oscillation')
# Second subplot
ax = fig.add_subplot(2, 1, 2, projection='3d')
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)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1,
linewidth=0, antialiased=False)
ax.set_zlim(-1, 1)
plt.show()
```
## 下载这个示例
- [下载python源码: mixed_subplots.py](https://matplotlib.org/_downloads/mixed_subplots.py)
- [下载Jupyter notebook: mixed_subplots.ipynb](https://matplotlib.org/_downloads/mixed_subplots.ipynb)

View File

@@ -0,0 +1,77 @@
# 自动文本偏移
演示如何使用pathpatch_2d_to_3d在3D绘图上“绘制”形状和文本。
![自动文本偏移示例](https://matplotlib.org/_images/sphx_glr_pathpatch3d_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import mpl_toolkits.mplot3d.art3d as art3d
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
'''
Plots the string 's' on the axes 'ax', with position 'xyz', size 'size',
and rotation angle 'angle'. 'zdir' gives the axis which is to be treated
as the third dimension. usetex is a boolean indicating whether the string
should be interpreted as latex or not. Any additional keyword arguments
are passed on to transform_path.
Note: zdir affects the interpretation of xyz.
'''
x, y, z = xyz
if zdir == "y":
xy1, z1 = (x, z), y
elif zdir == "x":
xy1, z1 = (y, z), x
else:
xy1, z1 = (x, y), z
text_path = TextPath((0, 0), s, size=size, usetex=usetex)
trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])
p1 = PathPatch(trans.transform_path(text_path), **kwargs)
ax.add_patch(p1)
art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Draw a circle on the x=0 'wall'
p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
# Manually label the axes
text3d(ax, (4, -2, 0), "X-axis", zdir="z", size=.5, usetex=False,
ec="none", fc="k")
text3d(ax, (12, 4, 0), "Y-axis", zdir="z", size=.5, usetex=False,
angle=np.pi / 2, ec="none", fc="k")
text3d(ax, (12, 10, 4), "Z-axis", zdir="y", size=.5, usetex=False,
angle=np.pi / 2, ec="none", fc="k")
# Write a Latex formula on the z=0 'floor'
text3d(ax, (1, 5, 0),
r"$\displaystyle G_{\mu\nu} + \Lambda g_{\mu\nu} = "
r"\frac{8\pi G}{c^4} T_{\mu\nu} $",
zdir="z", size=1, usetex=True,
ec="none", fc="k")
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
plt.show()
```
## 下载这个示例
- [下载python源码: pathpatch3d.py](https://matplotlib.org/_downloads/pathpatch3d.py)
- [下载Jupyter notebook: pathpatch3d.ipynb](https://matplotlib.org/_downloads/pathpatch3d.ipynb)

View File

@@ -0,0 +1,78 @@
# 在3D绘图中绘制平面对象
演示如何使用pathpatch_2d_to_3d在3D绘图上“绘制”形状和文本。
![在3D绘图中绘制平面对象示例](https://matplotlib.org/_images/sphx_glr_pathpatch3d_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.patches import Circle, PathPatch
from matplotlib.text import TextPath
from matplotlib.transforms import Affine2D
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import mpl_toolkits.mplot3d.art3d as art3d
def text3d(ax, xyz, s, zdir="z", size=None, angle=0, usetex=False, **kwargs):
'''
Plots the string 's' on the axes 'ax', with position 'xyz', size 'size',
and rotation angle 'angle'. 'zdir' gives the axis which is to be treated
as the third dimension. usetex is a boolean indicating whether the string
should be interpreted as latex or not. Any additional keyword arguments
are passed on to transform_path.
Note: zdir affects the interpretation of xyz.
'''
x, y, z = xyz
if zdir == "y":
xy1, z1 = (x, z), y
elif zdir == "x":
xy1, z1 = (y, z), x
else:
xy1, z1 = (x, y), z
text_path = TextPath((0, 0), s, size=size, usetex=usetex)
trans = Affine2D().rotate(angle).translate(xy1[0], xy1[1])
p1 = PathPatch(trans.transform_path(text_path), **kwargs)
ax.add_patch(p1)
art3d.pathpatch_2d_to_3d(p1, z=z1, zdir=zdir)
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Draw a circle on the x=0 'wall'
p = Circle((5, 5), 3)
ax.add_patch(p)
art3d.pathpatch_2d_to_3d(p, z=0, zdir="x")
# Manually label the axes
text3d(ax, (4, -2, 0), "X-axis", zdir="z", size=.5, usetex=False,
ec="none", fc="k")
text3d(ax, (12, 4, 0), "Y-axis", zdir="z", size=.5, usetex=False,
angle=np.pi / 2, ec="none", fc="k")
text3d(ax, (12, 10, 4), "Z-axis", zdir="y", size=.5, usetex=False,
angle=np.pi / 2, ec="none", fc="k")
# Write a Latex formula on the z=0 'floor'
text3d(ax, (1, 5, 0),
r"$\displaystyle G_{\mu\nu} + \Lambda g_{\mu\nu} = "
r"\frac{8\pi G}{c^4} T_{\mu\nu} $",
zdir="z", size=1, usetex=True,
ec="none", fc="k")
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
plt.show()
```
## 下载这个示例
- [下载python源码: pathpatch3d.py](https://matplotlib.org/_downloads/pathpatch3d.py)
- [下载Jupyter notebook: pathpatch3d.ipynb](https://matplotlib.org/_downloads/pathpatch3d.ipynb)

View File

@@ -0,0 +1,67 @@
# 生成多边形以填充3D线图
演示如何创建填充线图下空间的多边形。 在这个例子中,多边形是半透明的,产生一种“锯齿状的彩色玻璃”效果。
![生成多边形以填充3D线图示例](https://matplotlib.org/_images/sphx_glr_polys3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
from matplotlib.collections import PolyCollection
import matplotlib.pyplot as plt
from matplotlib import colors as mcolors
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
def cc(arg):
'''
Shorthand to convert 'named' colors to rgba format at 60% opacity.
'''
return mcolors.to_rgba(arg, alpha=0.6)
def polygon_under_graph(xlist, ylist):
'''
Construct the vertex list which defines the polygon filling the space under
the (xlist, ylist) line graph. Assumes the xs are in ascending order.
'''
return [(xlist[0], 0.), *zip(xlist, ylist), (xlist[-1], 0.)]
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make verts a list, verts[i] will be a list of (x,y) pairs defining polygon i
verts = []
# Set up the x sequence
xs = np.linspace(0., 10., 26)
# The ith polygon will appear on the plane y = zs[i]
zs = range(4)
for i in zs:
ys = np.random.rand(len(xs))
verts.append(polygon_under_graph(xs, ys))
poly = PolyCollection(verts, facecolors=[cc('r'), cc('g'), cc('b'), cc('y')])
ax.add_collection3d(poly, zs=zs, zdir='y')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
ax.set_xlim(0, 10)
ax.set_ylim(-1, 4)
ax.set_zlim(0, 1)
plt.show()
```
## 下载这个示例
- [下载python源码: polys3d.py](https://matplotlib.org/_downloads/polys3d.py)
- [下载Jupyter notebook: polys3d.ipynb](https://matplotlib.org/_downloads/polys3d.ipynb)

View File

@@ -0,0 +1,36 @@
# 3D箭袋图像
演示在3d网格上的点处绘制方向箭头。
![3D箭袋图像示例](https://matplotlib.org/_images/sphx_glr_quiver3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make the grid
x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
np.arange(-0.8, 1, 0.2),
np.arange(-0.8, 1, 0.8))
# Make the direction data for the arrows
u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z)
v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z)
w = (np.sqrt(2.0 / 3.0) * np.cos(np.pi * x) * np.cos(np.pi * y) *
np.sin(np.pi * z))
ax.quiver(x, y, z, u, v, w, length=0.1, normalize=True)
plt.show()
```
## 下载这个示例
- [下载python源码: quiver3d.py](https://matplotlib.org/_downloads/quiver3d.py)
- [下载Jupyter notebook: quiver3d.ipynb](https://matplotlib.org/_downloads/quiver3d.ipynb)

View File

@@ -0,0 +1,30 @@
# 旋转3D绘图
一个非常简单的旋转3D绘图动画。
有关动画3D绘图的另一个简单示例请参阅wire3d_animation_demo。
(构建文档库时会跳过此示例,因为它有意运行需要很长时间)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# load some test data for demonstration and plot a wireframe
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)
# rotate the axes and update
for angle in range(0, 360):
ax.view_init(30, angle)
plt.draw()
plt.pause(.001)
```
## 下载这个示例
- [下载python源码: rotate_axes3d_sgskip.py](https://matplotlib.org/_downloads/rotate_axes3d_sgskip.py)
- [下载Jupyter notebook: rotate_axes3d_sgskip.ipynb](https://matplotlib.org/_downloads/rotate_axes3d_sgskip.ipynb)

View File

@@ -0,0 +1,48 @@
# 3D散点图
演示3D中的基本散点图。
![3D散点图示例](https://matplotlib.org/_images/sphx_glr_scatter3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
# Fixing random state for reproducibility
np.random.seed(19680801)
def randrange(n, vmin, vmax):
'''
Helper function to make an array of random numbers having shape (n, )
with each number distributed Uniform(vmin, vmax).
'''
return (vmax - vmin)*np.random.rand(n) + vmin
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
n = 100
# For each set of style and range settings, plot n random points in the box
# defined by x in [23, 32], y in [0, 100], z in [zlow, zhigh].
for c, m, zlow, zhigh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
xs = randrange(n, 23, 32)
ys = randrange(n, 0, 100)
zs = randrange(n, zlow, zhigh)
ax.scatter(xs, ys, zs, c=c, marker=m)
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
plt.show()
```
## 下载这个示例
- [下载python源码: scatter3d.py](https://matplotlib.org/_downloads/scatter3d.py)
- [下载Jupyter notebook: scatter3d.ipynb](https://matplotlib.org/_downloads/scatter3d.ipynb)

View File

@@ -0,0 +1,53 @@
# 3D绘图作为子图
展示包括3D图作为子图。
![3D绘图作为子图示例](https://matplotlib.org/_images/sphx_glr_subplot3d_001.png)
```python
import matplotlib.pyplot as plt
from matplotlib import cm
import numpy as np
from mpl_toolkits.mplot3d.axes3d import get_test_data
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
# set up a figure twice as wide as it is tall
fig = plt.figure(figsize=plt.figaspect(0.5))
#===============
# First subplot
#===============
# set up the axes for the first plot
ax = fig.add_subplot(1, 2, 1, projection='3d')
# plot a 3D surface like in the example mplot3d/surface3d_demo
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)
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)
fig.colorbar(surf, shrink=0.5, aspect=10)
#===============
# Second subplot
#===============
# set up the axes for the second plot
ax = fig.add_subplot(1, 2, 2, projection='3d')
# plot a 3D wireframe like in the example mplot3d/wire3d_demo
X, Y, Z = get_test_data(0.05)
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
```
## 下载这个示例
- [下载python源码: subplot3d.py](https://matplotlib.org/_downloads/subplot3d.py)
- [下载Jupyter notebook: subplot3d.ipynb](https://matplotlib.org/_downloads/subplot3d.ipynb)

View File

@@ -0,0 +1,47 @@
# 三维曲面(颜色贴图)
演示绘制使用coolwarm颜色贴图着色的3D表面。 使用antialiased = False使表面变得不透明。
还演示了使用LinearLocator和z轴刻度标签的自定义格式。
![三维曲面(颜色贴图)示例](https://matplotlib.org/_images/sphx_glr_surface3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
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)
# Customize the z axis.
ax.set_zlim(-1.01, 1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
# Add a color bar which maps values to colors.
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.show()
```
## 下载这个示例
- [下载python源码: surface3d.py](https://matplotlib.org/_downloads/surface3d.py)
- [下载Jupyter notebook: surface3d.ipynb](https://matplotlib.org/_downloads/surface3d.ipynb)

View File

@@ -0,0 +1,34 @@
# 三维曲面(纯色)
使用纯色演示3D表面的基本图。
![三维曲面(纯色)示例](https://matplotlib.org/_images/sphx_glr_surface3d_2_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Make data
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)
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))
# Plot the surface
ax.plot_surface(x, y, z, color='b')
plt.show()
```
## 下载这个示例
- [下载python源码: surface3d_2.py](https://matplotlib.org/_downloads/surface3d_2.py)
- [下载Jupyter notebook: surface3d_2.ipynb](https://matplotlib.org/_downloads/surface3d_2.ipynb)

View File

@@ -0,0 +1,49 @@
# 三维曲面(棋盘格)
演示绘制以棋盘图案着色的3D表面。
![三维曲面(棋盘格)示例](https://matplotlib.org/_images/sphx_glr_surface3d_3_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
from matplotlib.ticker import LinearLocator
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
# Make data.
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)
# Create an empty array of strings with the same shape as the meshgrid, and
# populate it with two colors in a checkerboard pattern.
colortuple = ('y', 'b')
colors = np.empty(X.shape, dtype=str)
for y in range(ylen):
for x in range(xlen):
colors[x, y] = colortuple[(x + y) % len(colortuple)]
# Plot the surface with face colors taken from the array we made.
surf = ax.plot_surface(X, Y, Z, facecolors=colors, linewidth=0)
# Customize the z axis.
ax.set_zlim(-1, 1)
ax.w_zaxis.set_major_locator(LinearLocator(6))
plt.show()
```
## 下载这个示例
- [下载python源码: surface3d_3.py](https://matplotlib.org/_downloads/surface3d_3.py)
- [下载Jupyter notebook: surface3d_3.ipynb](https://matplotlib.org/_downloads/surface3d_3.ipynb)

View File

@@ -0,0 +1,44 @@
# 极坐标下的三维曲面
演示绘制在极坐标中定义的曲面。使用YlGnBu颜色映射的反转版本。还演示了使用乳胶数学模式编写轴标签。
示例由Armin Moser提供。
![极坐标下的三维曲面示例](https://matplotlib.org/_images/sphx_glr_surface3d_radial_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Create the mesh in polar coordinates and compute corresponding Z.
r = np.linspace(0, 1.25, 50)
p = np.linspace(0, 2*np.pi, 50)
R, P = np.meshgrid(r, p)
Z = ((R**2 - 1)**2)
# Express the mesh in the cartesian system.
X, Y = R*np.cos(P), R*np.sin(P)
# Plot the surface.
ax.plot_surface(X, Y, Z, cmap=plt.cm.YlGnBu_r)
# Tweak the limits and add latex math labels.
ax.set_zlim(0, 1)
ax.set_xlabel(r'$\phi_\mathrm{real}$')
ax.set_ylabel(r'$\phi_\mathrm{im}$')
ax.set_zlabel(r'$V(\phi)$')
plt.show()
```
## 下载这个示例
- [下载python源码: surface3d_radial.py](https://matplotlib.org/_downloads/surface3d_radial.py)
- [下载Jupyter notebook: surface3d_radial.ipynb](https://matplotlib.org/_downloads/surface3d_radial.ipynb)

View File

@@ -0,0 +1,53 @@
# 三维中的文字注释
演示在3D绘图上放置文本注释。
显示的功能:
- 使用具有三种“zdir”值的文本函数轴名称例如'x'或方向元组例如1,1,0
- 使用带有color关键字的文本功能。
- 使用text2D函数将文本放在ax对象上的固定位置。
![三维中的文字注释示例](https://matplotlib.org/_images/sphx_glr_text3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
# Demo 1: zdir
zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1))
xs = (1, 4, 4, 9, 4, 1)
ys = (2, 5, 8, 10, 1, 2)
zs = (10, 3, 8, 9, 1, 8)
for zdir, x, y, z in zip(zdirs, xs, ys, zs):
label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir)
ax.text(x, y, z, label, zdir)
# Demo 2: color
ax.text(9, 0, 0, "red", color='red')
# Demo 3: text2D
# Placement 0, 0 would be the bottom left, 1, 1 would be the top right.
ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes)
# Tweaking display region and labels
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.set_zlim(0, 10)
ax.set_xlabel('X axis')
ax.set_ylabel('Y axis')
ax.set_zlabel('Z axis')
plt.show()
```
## 下载这个示例
- [下载python源码: text3d.py](https://matplotlib.org/_downloads/text3d.py)
- [下载Jupyter notebook: text3d.ipynb](https://matplotlib.org/_downloads/text3d.ipynb)

View File

@@ -0,0 +1,52 @@
# 三角形三维等高线图
非结构化三角形网格的等高线图。
使用的数据与trisurf3d_demo2的第二个图中的数据相同。 tricontourf3d_demo显示此示例的填充版本。
![三角形三维等高线图示例](https://matplotlib.org/_images/sphx_glr_tricontour3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
n_angles = 48
n_radii = 8
min_radius = 0.25
# Create the mesh in polar coordinates and compute x, y, z.
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(3*angles)).flatten()
# Create a custom triangulation.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.tricontour(triang, z, cmap=plt.cm.CMRmap)
# Customize the view angle so it's easier to understand the plot.
ax.view_init(elev=45.)
plt.show()
```
## 下载这个示例
- [下载python源码: tricontour3d.py](https://matplotlib.org/_downloads/tricontour3d.py)
- [下载Jupyter notebook: tricontour3d.ipynb](https://matplotlib.org/_downloads/tricontour3d.ipynb)

View File

@@ -0,0 +1,53 @@
# 三角形三维填充等高线图
非结构化三角形网格的填充等高线图。
使用的数据与trisurf3d_demo2的第二个图中的数据相同。 tricontour3d_demo显示此示例的未填充版本。
![三角形三维填充等高线图示例](https://matplotlib.org/_images/sphx_glr_tricontourf3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np
# First create the x, y, z coordinates of the points.
n_angles = 48
n_radii = 8
min_radius = 0.25
# Create the mesh in polar coordinates and compute x, y, z.
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(3*angles)).flatten()
# Create a custom triangulation.
triang = tri.Triangulation(x, y)
# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
y[triang.triangles].mean(axis=1))
< min_radius)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.tricontourf(triang, z, cmap=plt.cm.CMRmap)
# Customize the view angle so it's easier to understand the plot.
ax.view_init(elev=45.)
plt.show()
```
## 下载这个示例
- [下载python源码: tricontourf3d.py](https://matplotlib.org/_downloads/tricontourf3d.py)
- [下载Jupyter notebook: tricontourf3d.ipynb](https://matplotlib.org/_downloads/tricontourf3d.ipynb)

View File

@@ -0,0 +1,42 @@
# 三角三维曲面
用三角形网格绘制3D表面。
![三角三维曲面示例](https://matplotlib.org/_images/sphx_glr_trisurf3d_001.png)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
n_radii = 8
n_angles = 36
# Make radii and angles spaces (radius r=0 omitted to eliminate duplication).
radii = np.linspace(0.125, 1.0, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)[..., np.newaxis]
# Convert polar (radii, angles) coords to cartesian (x, y) coords.
# (0, 0) is manually added at this stage, so there will be no duplicate
# points in the (x, y) plane.
x = np.append(0, (radii*np.cos(angles)).flatten())
y = np.append(0, (radii*np.sin(angles)).flatten())
# Compute z to make the pringle surface.
z = np.sin(-x*y)
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.plot_trisurf(x, y, z, linewidth=0.2, antialiased=True)
plt.show()
```
## 下载这个示例
- [下载python源码: trisurf3d.py](https://matplotlib.org/_downloads/trisurf3d.py)
- [下载Jupyter notebook: trisurf3d.ipynb](https://matplotlib.org/_downloads/trisurf3d.ipynb)

View File

@@ -0,0 +1,85 @@
# 多三角三维曲面
使用三角形网格绘制曲面的另外两个示例。
第一个演示使用plot_trisurf的三角形参数第二个设置Triangulation对象的蒙版并将对象直接传递给plot_trisurf。
![多三角三维曲面示例](https://matplotlib.org/_images/sphx_glr_trisurf3d_2_001.png)
```python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.tri as mtri
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
fig = plt.figure(figsize=plt.figaspect(0.5))
#============
# First plot
#============
# Make a mesh in the space of parameterisation variables u and v
u = np.linspace(0, 2.0 * np.pi, endpoint=True, num=50)
v = np.linspace(-0.5, 0.5, endpoint=True, num=10)
u, v = np.meshgrid(u, v)
u, v = u.flatten(), v.flatten()
# This is the Mobius mapping, taking a u, v pair and returning an x, y, z
# triple
x = (1 + 0.5 * v * np.cos(u / 2.0)) * np.cos(u)
y = (1 + 0.5 * v * np.cos(u / 2.0)) * np.sin(u)
z = 0.5 * v * np.sin(u / 2.0)
# Triangulate parameter space to determine the triangles
tri = mtri.Triangulation(u, v)
# Plot the surface. The triangles in parameter space determine which x, y, z
# points are connected by an edge.
ax = fig.add_subplot(1, 2, 1, projection='3d')
ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap=plt.cm.Spectral)
ax.set_zlim(-1, 1)
#============
# Second plot
#============
# Make parameter spaces radii and angles.
n_angles = 36
n_radii = 8
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += np.pi/n_angles
# Map radius, angle pairs to x, y, z points.
x = (radii*np.cos(angles)).flatten()
y = (radii*np.sin(angles)).flatten()
z = (np.cos(radii)*np.cos(3*angles)).flatten()
# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = mtri.Triangulation(x, y)
# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = np.where(xmid**2 + ymid**2 < min_radius**2, 1, 0)
triang.set_mask(mask)
# Plot the surface.
ax = fig.add_subplot(1, 2, 2, projection='3d')
ax.plot_trisurf(triang, z, cmap=plt.cm.CMRmap)
plt.show()
```
## 下载这个示例
- [下载python源码: trisurf3d_2.py](https://matplotlib.org/_downloads/trisurf3d_2.py)
- [下载Jupyter notebook: trisurf3d_2.ipynb](https://matplotlib.org/_downloads/trisurf3d_2.ipynb)

View File

@@ -0,0 +1,43 @@
# 三维体素/体积绘制
演示使用ax.voxels绘制3D体积对象
![三维体素/体积绘制示例](https://matplotlib.org/_images/sphx_glr_voxels_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
# prepare some coordinates
x, y, z = np.indices((8, 8, 8))
# draw cuboids in the top left and bottom right corners, and a link between them
cube1 = (x < 3) & (y < 3) & (z < 3)
cube2 = (x >= 5) & (y >= 5) & (z >= 5)
link = abs(x - y) + abs(y - z) + abs(z - x) <= 2
# combine the objects into a single boolean array
voxels = cube1 | cube2 | link
# set the colors of each object
colors = np.empty(voxels.shape, dtype=object)
colors[link] = 'red'
colors[cube1] = 'blue'
colors[cube2] = 'green'
# and plot everything
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(voxels, facecolors=colors, edgecolor='k')
plt.show()
```
## 下载这个示例
- [下载python源码: voxels.py](https://matplotlib.org/_downloads/voxels.py)
- [下载Jupyter notebook: voxels.ipynb](https://matplotlib.org/_downloads/voxels.ipynb)

View File

@@ -0,0 +1,55 @@
# 三维体素绘制Numpy的Logo
演示使用坐标不均匀的ax.voxels
![三维体素绘制Numpy的Logo示例](https://matplotlib.org/_images/sphx_glr_voxels_numpy_logo_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
def explode(data):
size = np.array(data.shape)*2
data_e = np.zeros(size - 1, dtype=data.dtype)
data_e[::2, ::2, ::2] = data
return data_e
# build up the numpy logo
n_voxels = np.zeros((4, 3, 4), dtype=bool)
n_voxels[0, 0, :] = True
n_voxels[-1, 0, :] = True
n_voxels[1, 0, 2] = True
n_voxels[2, 0, 1] = True
facecolors = np.where(n_voxels, '#FFD65DC0', '#7A88CCC0')
edgecolors = np.where(n_voxels, '#BFAB6E', '#7D84A6')
filled = np.ones(n_voxels.shape)
# upscale the above voxel image, leaving gaps
filled_2 = explode(filled)
fcolors_2 = explode(facecolors)
ecolors_2 = explode(edgecolors)
# Shrink the gaps
x, y, z = np.indices(np.array(filled_2.shape) + 1).astype(float) // 2
x[0::2, :, :] += 0.05
y[:, 0::2, :] += 0.05
z[:, :, 0::2] += 0.05
x[1::2, :, :] += 0.95
y[:, 1::2, :] += 0.95
z[:, :, 1::2] += 0.95
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(x, y, z, filled_2, facecolors=fcolors_2, edgecolors=ecolors_2)
plt.show()
```
## 下载这个示例
- [下载python源码: voxels_numpy_logo.py](https://matplotlib.org/_downloads/voxels_numpy_logo.py)
- [下载Jupyter notebook: voxels_numpy_logo.ipynb](https://matplotlib.org/_downloads/voxels_numpy_logo.ipynb)

View File

@@ -0,0 +1,52 @@
# 带有rgb颜色的3D体素/体积图
演示使用ax.voxels可视化颜色空间的各个部分
![带有rgb颜色的3D体素/体积图示例](https://matplotlib.org/_images/sphx_glr_voxels_rgb_001.png)
```python
import matplotlib.pyplot as plt
import numpy as np
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
def midpoints(x):
sl = ()
for i in range(x.ndim):
x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
sl += np.index_exp[:]
return x
# prepare some coordinates, and attach rgb values to each
r, g, b = np.indices((17, 17, 17)) / 16.0
rc = midpoints(r)
gc = midpoints(g)
bc = midpoints(b)
# define a sphere about [0.5, 0.5, 0.5]
sphere = (rc - 0.5)**2 + (gc - 0.5)**2 + (bc - 0.5)**2 < 0.5**2
# combine the color components
colors = np.zeros(sphere.shape + (3,))
colors[..., 0] = rc
colors[..., 1] = gc
colors[..., 2] = bc
# and plot everything
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(r, g, b, sphere,
facecolors=colors,
edgecolors=np.clip(2*colors - 0.5, 0, 1), # brighter
linewidth=0.5)
ax.set(xlabel='r', ylabel='g', zlabel='b')
plt.show()
```
## 下载这个示例
- [下载python源码: voxels_rgb.py](https://matplotlib.org/_downloads/voxels_rgb.py)
- [下载Jupyter notebook: voxels_rgb.ipynb](https://matplotlib.org/_downloads/voxels_rgb.ipynb)

View File

@@ -0,0 +1,54 @@
# 具有圆柱坐标的3D体素/体积图
演示使用ax.voxels的xyz参数。
![具有圆柱坐标的3D体素/体积图示例](https://matplotlib.org/_images/sphx_glr_voxels_torus_001.png)
```python
import matplotlib.pyplot as plt
import matplotlib.colors
import numpy as np
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
def midpoints(x):
sl = ()
for i in range(x.ndim):
x = (x[sl + np.index_exp[:-1]] + x[sl + np.index_exp[1:]]) / 2.0
sl += np.index_exp[:]
return x
# prepare some coordinates, and attach rgb values to each
r, theta, z = np.mgrid[0:1:11j, 0:np.pi*2:25j, -0.5:0.5:11j]
x = r*np.cos(theta)
y = r*np.sin(theta)
rc, thetac, zc = midpoints(r), midpoints(theta), midpoints(z)
# define a wobbly torus about [0.7, *, 0]
sphere = (rc - 0.7)**2 + (zc + 0.2*np.cos(thetac*2))**2 < 0.2**2
# combine the color components
hsv = np.zeros(sphere.shape + (3,))
hsv[..., 0] = thetac / (np.pi*2)
hsv[..., 1] = rc
hsv[..., 2] = zc + 0.5
colors = matplotlib.colors.hsv_to_rgb(hsv)
# and plot everything
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.voxels(x, y, z, sphere,
facecolors=colors,
edgecolors=np.clip(2*colors - 0.5, 0, 1), # brighter
linewidth=0.5)
plt.show()
```
## 下载这个示例
- [下载python源码: voxels_torus.py](https://matplotlib.org/_downloads/voxels_torus.py)
- [下载Jupyter notebook: voxels_torus.ipynb](https://matplotlib.org/_downloads/voxels_torus.ipynb)

View File

@@ -0,0 +1,27 @@
# 3D线框图
线框图的一个非常基本的演示。
![3D线框图示例](https://matplotlib.org/_images/sphx_glr_wire3d_001.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Grab some test data.
X, Y, Z = axes3d.get_test_data(0.05)
# Plot a basic wireframe.
ax.plot_wireframe(X, Y, Z, rstride=10, cstride=10)
plt.show()
```
## 下载这个示例
- [下载python源码: wire3d.py](https://matplotlib.org/_downloads/wire3d.py)
- [下载Jupyter notebook: wire3d.ipynb](https://matplotlib.org/_downloads/wire3d.ipynb)

View File

@@ -0,0 +1,54 @@
# 旋转3D线框图
一个非常简单的3D动画“动画”。 另请参见rotate_axes3d_demo。
(构建文档库时会跳过此示例,因为它有意运行需要很长时间)
```python
# This import registers the 3D projection, but is otherwise unused.
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import matplotlib.pyplot as plt
import numpy as np
import time
def generate(X, Y, phi):
'''
Generates Z data for the points in the X, Y meshgrid and parameter phi.
'''
R = 1 - np.sqrt(X**2 + Y**2)
return np.cos(2 * np.pi * X + phi) * R
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Make the X, Y meshgrid.
xs = np.linspace(-1, 1, 50)
ys = np.linspace(-1, 1, 50)
X, Y = np.meshgrid(xs, ys)
# Set the z axis limits so they aren't recalculated each frame.
ax.set_zlim(-1, 1)
# Begin plotting.
wframe = None
tstart = time.time()
for phi in np.linspace(0, 180. / np.pi, 100):
# If a line collection is already remove it before drawing.
if wframe:
ax.collections.remove(wframe)
# Plot the new wireframe and pause briefly before continuing.
Z = generate(X, Y, phi)
wframe = ax.plot_wireframe(X, Y, Z, rstride=2, cstride=2)
plt.pause(.001)
print('Average FPS: %f' % (100 / (time.time() - tstart)))
```
## 下载这个示例
- [下载python源码: wire3d_animation_sgskip.py](https://matplotlib.org/_downloads/wire3d_animation_sgskip.py)
- [下载Jupyter notebook: wire3d_animation_sgskip.ipynb](https://matplotlib.org/_downloads/wire3d_animation_sgskip.ipynb)

View File

@@ -0,0 +1,32 @@
# 三维线框在一个方向上绘制
证明将rstride或cstride设置为0会导致在相应方向上不生成导线。
![三维线框在一个方向上绘制示例](https://matplotlib.org/_images/sphx_glr_wire3d_zero_stride_001.png)
```python
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig, [ax1, ax2] = plt.subplots(2, 1, figsize=(8, 12), subplot_kw={'projection': '3d'})
# Get the test data
X, Y, Z = axes3d.get_test_data(0.05)
# Give the first plot only wireframes of the type y = c
ax1.plot_wireframe(X, Y, Z, rstride=10, cstride=0)
ax1.set_title("Column (x) stride set to 0")
# Give the second plot only wireframes of the type x = c
ax2.plot_wireframe(X, Y, Z, rstride=0, cstride=10)
ax2.set_title("Row (y) stride set to 0")
plt.tight_layout()
plt.show()
```
## 下载这个示例
- [下载python源码: wire3d_zero_stride.py](https://matplotlib.org/_downloads/wire3d_zero_stride.py)
- [下载Jupyter notebook: wire3d_zero_stride.ipynb](https://matplotlib.org/_downloads/wire3d_zero_stride.ipynb)