2017-10-18 66 views
2

此代碼顯示兩個Sympy地塊爲兩個Matplotlib副區

from sympy import * 
x=Symbol('x') 
p1 = plot(x**2,(x,-2,2)) 
p2 = plot(x**3,(x,-2,2)) 

結果在兩個分開的地塊。

而不是兩個獨立的情節,我想與matplotlib的次要情節,以顯示他們:

import matplotlib.pyplot as plt 
fig = plt.figure() 
ax1 = fig.add_subplot(121) 
ax2 = fig.add_subplot(122) 
plt.show() 

如何添加p1p2,讓他們顯示爲matplotlib圖裏面的次要情節?

+1

我可能是錯的。但sympy的情節似乎並沒有採用''ax'''參數,一切似乎都基於數字。我認爲matplotlib的狀態仍然是:合併多個數字至少是hacky,不推薦。 (對於這個例子,我不直接使用mpl對我來說沒有什麼意義;但是對於你的真實任務也許會有所不同)。 – sascha

回答

4

問題是sympy Plot創建它自己的圖形和座標軸。這並不意味着要繪製到現有的座標軸。

您可能然而通過之前表示sympy情節現有軸替換積被吸引到軸。

from sympy import Symbol,plot 
import matplotlib.pyplot as plt 

def move_sympyplot_to_axes(p, ax): 
    backend = p.backend(p) 
    backend.ax = ax 
    backend.process_series() 
    backend.ax.spines['right'].set_color('none') 
    backend.ax.spines['bottom'].set_position('zero') 
    backend.ax.spines['top'].set_color('none') 
    plt.close(backend.fig) 


x=Symbol('x') 
p1 = plot(x**2,(x,-2,2), show=False) 
p2 = plot(x**3,(x,-2,2), show=False) 


fig, (ax,ax2) = plt.subplots(ncols=2) 
move_sympyplot_to_axes(p1, ax) 
move_sympyplot_to_axes(p2, ax2) 

plt.show() 

enter image description here

+0

這是我需要記住的未來。我已經檢查過這些後端屬性,但無法使用它們。你在這裏定義的* hacky *是什麼?非漂亮的代碼或擔心即將matplotlib變化? – sascha

+1

@sascha從matplotlib方面看,這沒什麼問題。通過hacky我的意思是沒有真正使用任何API。該解決方案首先防止sympy「後端」密謀什麼,然後人爲地把自身的一個屬性,然後手動調用什麼它'show'方法會做一部分。所以,猴子打補丁的方式也很糟糕。 – ImportanceOfBeingErnest

3

我的解決方案中不添加p1p2直接的次要情節。但是(x,y)座標將被捕獲並使用。

import matplotlib.pyplot as plt 
from sympy import symbols 
import numpy as np 

from sympy import symbols 
from sympy.plotting import plot 

# part 1 
# uses symbolic plot of functions 
x = symbols('x') 

#p1, p2 = plot(x**2, x**3, (x, -2, 2)) 

# this plot will not show ... 
# only produce 2 curves 
p1, p2 = plot((x**2, (x, -2, 2)), \ 
       (x**3, (x, -2, 2)), \ 
       show=False) 

# collect (x,y)'s of the unseen curves 
x1y1 = p1.get_points() # array of 2D 
x2y2 = p2.get_points() 

# part 2 
# uses regular matplotlib to plot the data 

fig = plt.figure(figsize=(8, 5)) 
ax1 = fig.add_subplot(121) 
ax2 = fig.add_subplot(122) 

# do subplot 1 
ax1.plot(x1y1[0], x1y1[1], 'g') # plot x**2 in green 
ax1.set_xlim([-2, 2]) 
ax1.set_xlabel('X1') 
ax1.set_ylabel('Y1') 
ax1.set_title('Line1') # destroyed by another .title(); axis metho1 

# do subplot 2 
ax2.plot(x2y2[0], x2y2[1], 'r') # plot x**3 in red 
ax2.set_xlim([-2, 2]) 
ax2.set_xlabel('X2') 
ax2.set_ylabel('Y2') 
ax2.set_title('Line2') 

fig.subplots_adjust(wspace=0.4) # set space between subplots 

plt.show() 

所得的情節:

output

+1

雖然少將軍,也許不是OP問,我看到在某些情況下,這是可行的選擇! – sascha