在3D图中裁剪轮廓线f()图

时间:2020-01-17 07:22:52

标签: python matplotlib

我正在使用contourf用圆形3D绘制多个密度图。

我想做的事情类似于clip_path情节的pcolormesh。 如何特别是针对contourf绘图以3D裁剪绘图?

picture

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches

fig    = plt.figure()
ax     = fig.gca(projection='3d')

x      = np.linspace(0, 1, 100)
X, Y   = np.meshgrid(x, x)
levels = np.linspace(-0.1, 0.4, 100)  #(z_min,z_max,number of contour),

a=0
b=1
c=2
Z1 = a+.1*np.sin(2*X)*np.sin(4*Y)
Z2 = b+.1*np.sin(3*X)*np.sin(4*Y)
Z3 = c+.1*np.sin(4*X)*np.sin(5*Y)

plt.contourf(X, Y,Z1, levels=a+levels,cmap=plt.get_cmap('rainbow'))
plt.contourf(X, Y,Z2, levels=b+levels,cmap=plt.get_cmap('rainbow'))
plt.contourf(X, Y,Z3, levels=c+levels,cmap=plt.get_cmap('rainbow'))

ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 2)

plt.show()

1 个答案:

答案 0 :(得分:2)

您确定您的代码使用给定的参数生成了该输出图像吗?我只有一些蓝色方块。稍作调整,它就会开始看起来像您一样。

要裁剪轮廓,请考虑masking Z数组。如:

from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
import numpy.ma as ma

fig    = plt.figure()
ax     = fig.gca(projection='3d')

x      = np.linspace(0, 1, 100)
X, Y   = np.meshgrid(x, x)
levels = np.linspace(-0.1, 0.4, 100)  #(z_min,z_max,number of contour),

a = 0
b = 1
c = 2
Z1 = a + .3 * np.sin(2 * X) * np.sin(4 * Y)
Z2 = b + .3 * np.sin(3 * X) * np.sin(4 * Y)
Z3 = c + .3 * np.sin(4 * X) * np.sin(5 * Y)

mask_cond = (X - .5) ** 2 + (Y - .5) ** 2 > .25
Z1 = ma.masked_where(mask_cond, Z1)
Z2 = ma.masked_where(mask_cond, Z2)
Z3 = ma.masked_where(mask_cond, Z3)

plt.contourf(X, Y, Z1, levels=a + levels, cmap='rainbow')
plt.contourf(X, Y, Z2, levels=b + levels, cmap='rainbow')
plt.contourf(X, Y, Z3, levels=c + levels, cmap='rainbow')

ax.set_xlim3d(0, 1)
ax.set_ylim3d(0, 1)
ax.set_zlim3d(0, 3)

plt.show()

example plot