Matplotlib - mplot3d:在3d图中投影在z = 0轴上的triplot?

时间:2014-06-20 20:47:21

标签: python matplotlib plot triangulation mplot3d

我试图在两个变量中绘制函数,在一组已知三角形上分段定义,或多或少如此:

import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import random

def f( x, y):
  if x + y < 1: return 0
  else: return 1

x = [0, 1, 1, 0]
y = [0, 0, 1, 1]
tris = [[0, 1, 3], [1, 2,3]]

fig = plt.figure()
ax = fig.add_subplot( 121)
ax.triplot( x, y, tris)

xs = [random.random() for _ in range( 100)]
ys = [random.random() for _ in range( 100)]
zs = [f(xs[i], ys[i]) for i in range( 100)]
ax2 = fig.add_subplot( 122, projection='3d')
ax2.scatter( xs, ys, zs)
plt.show()

理想情况下,我通过将三角形投影到轴z = 0上将两个子图组合成一个。我知道这可能与2d图的其他变体有关,但不适用于triplot。是否有可能得到我想要的东西?

PS。这是我现在使用的实际实现的大大简化版本,因此随机散射可能看起来有点奇怪。

1 个答案:

答案 0 :(得分:0)

我不是专家,但这是一个有趣的问题。在做了一些探讨之后,我想我已经接近了。我手动制作了Triangulation对象,然后将它和z的零列表传递给plot_trisurf,它将三角形放在z = 0的正确位置。

import matplotlib.pyplot as plt
import matplotlib.tri as tri
from mpl_toolkits.mplot3d import Axes3D
import random

def f( x, y):
    if x + y < 1: return 0
    else: return 1

x = [0, 1, 1, 0]
y = [0, 0, 1, 1]
tris = [[0, 1, 3], [1, 2,3]]
z = [0] * 4

triv = tri.Triangulation(x, y, tris)

fig = plt.figure()
ax = fig.add_subplot( 111, projection='3d')
trip = ax.plot_trisurf( triv, z )
trip.set_facecolor('white')

xs = [random.random() for _ in range( 100)]
ys = [random.random() for _ in range( 100)]
zs = [f(xs[i], ys[i]) for i in range( 100)]

ax.scatter( xs, ys, zs)
plt.show()

ETA:在Poly3DCollection上添加了对set_facecolor的调用,使其变为白色,而不是遵循色彩映射。可以达到预期的效果......

相关问题