2011-10-31 140 views
2

我有一個matplotlib圖,我希望能夠在2D和3D投影之間切換。我可以從2D轉到3D,但我似乎無法弄清楚如何去其他方式。例如...matplotlib 3d回到2d

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是與問題相關還是暗示我的設置出現其他問題?投影從3D轉換到2D有沒有kwarg?

非常感謝您提供的任何指針。 Dan

回答

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() 
0

讓我開始說,如果您通過去實際使用以前的問題來回答您的接受率(目前爲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() 
+0

感謝您的輸入cosmosis。我錯過了接受和投票有用的不是同一件事!現在糾正我的錯誤。 我想我的問題必須有點模糊,因爲我的簡單例子。我希望能夠在2D和3D投影之間切換一個數字,而不是創建一個或另一個。該圖在wxPython GUI中的畫布上。任何想法如何實現? – Dan

1

我有同樣的問題,並嘗試接受的解決方案(由丹發佈)。它的工作,但給了我以下警告:

"UserWarning: This figure includes Axes that are not compatible with tight_layout, so its results might be incorrect."

但是,如果我使用:

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

然後它沒有任何警告。