matplotlib 3d回到2d

时间:2011-10-31 02:14:32

标签: python wxpython matplotlib

我有一个matplotlib图,我希望能够在2D和3D投影之间切换。我可以从2D到3D但我似乎无法弄清楚如何走另一条路。实施例...

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

def randrange(n, vmin, vmax):
    return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()

# Create a 3D scatter plot...
ax = fig.add_subplot(111, projection='3d')
n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
    xs = randrange(n, 23, 32)
    ys = randrange(n, 0, 100)
    zs = randrange(n, zl, zh)
    ax.scatter(xs, ys, zs, c=c, marker=m)

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')

# Now I want a 2D plot...
ax.cla()
ax = fig.add_subplot(111)
ax.plot(xs, ys)

plt.show()

情节保留在3D投影中,投影=“2D”不是有效的kwarg ......

我想也许ax.clf()可以做我想做的事情,让我定义一个新的数字。但它只是给我以下错误:    ValueError:未知元素o

任何人都可以给我一个解决方案吗? ValueError是否与问题相关或者我的设置有其他错误提示?是否有一个kwarg将投影从3D切换到2D?

非常感谢您提供的任何指针。 丹

3 个答案:

答案 0 :(得分:2)

我相信我找到了一个可能的解决方案,虽然它似乎会导致一些内存问题。我怀疑它实际上并没有删除初始绘图数据,只是将其从图中删除,因此每次更改投影时内存使用量都会上升。

# Delete the 3D subplot
self.fig.delaxes(self.axes)
# Create a new subplot that is 2D
self.axes = self.fig.add_subplot(111)
# 2D scatter
self.axes.plot(10*np.random.randn(100), 10*np.random.randn(100), 'o')
# Update the figure
self.canvas.draw()

答案 1 :(得分:1)

首先我要说的是,如果你提高了你的录取率(目前是0%),你可以通过去除你之前使用过的问题的答案来划分答案,那么也许更多的人愿意帮助你。

现在,为了回答你的问题,没有'2d'预测kwarg。但是,如果您希望通过并快速决定所需的投影类型,具体取决于关键字“q”,以下内容可为您提供帮助。我还改变了基本设置,以避免在不同类型的绘图之间产生混淆,因为你在循环之外有一些绘图调用,并且通常会清理你的组织。

希望这有帮助。

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

def randrange(n, vmin, vmax):
   return (vmax-vmin)*np.random.rand(n) + vmin

fig = plt.figure()
plt.clf()

q='2d'

n = 100
for c, m, zl, zh in [('r', 'o', -50, -25), ('b', '^', -30, -5)]:
  xs = randrange(n, 23, 32)
  ys = randrange(n, 0, 100)  
  zs = randrange(n, zl, zh)

if q=='3d':

  # Create a 3D scatter plot...
  ax = fig.add_subplot(111, projection='3d')
  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()

else:
  plt.clf()
  ax = fig.add_subplot(111)
  ax.plot(xs, ys)
  ax.set_xlabel('X Label')
  ax.set_ylabel('Y Label')
  plt.show()

答案 2 :(得分:1)

我遇到了同样的问题并尝试了接受的解决方案(Dan发布)。它奏效了,但给了我以下警告:

  

“UserWarning:此图包含与之不兼容的轴   tight_layout,所以结果可能不正确。“

但是,如果我使用:

self.figure.clf()
self.axes = self.figure.add_subplot(111)

然后它没有任何警告。

相关问题