2014-02-11 291 views
0

在下面的代碼中,a,b,c代表三個表達式:10x + 7y = 200,11x-8y = 63和x + y = 42。我想繪製這些表達式的每一個,我不確定最好的方法是什麼。用matplotlib從兩個列表中繪製多條線

當我得到下面的代碼:

import matplotlib.pyplot as plt 

#Set minimum graph boundary 
xMin = 0 
yMin = 0 

#a,b,c variables pulled from multiple expressions (ax+by=c) 
a = [10,11,1] 
b = [7,-8,1] 
c = [200,63,42] 

def init(): 
    #Create x,y lists // These will contain x,y plots 
    x = [] 
    y = [] 

    def findxy(a,b,c): 
    #Analyzes instances of (ax+by=c) and returns x,y; appends them to lists 

     #Finds x,y for ax+by=c 
     x.append((-b*yMin)/a + c/a) 
     y.append((-a*xMin)/b + c/b) 

    def printxy(x,y): 
     #Prints results of findxy, followed by "z = 15x + 15y" 
     if x >= xMin: 
      print '(%s, %s)' % (x,yMin), 15 * x + 15 * yMin 
     if y >= yMin: 
      print '(%s, %s)' % (xMin,y), 15 * xMin + 15 * y 

map(findxy,a,b,c) 
map(printxy,x,y) 

plt.plot(x,y) 
plt.show() 

...我得到以下結果:

>>> 
(20, 0) 300 
(0, 28) 420 
(5, 0) 75 
(42, 0) 630 
(0, 42) 630 

...其中,(20,0),(0,28)代表第一個表達式,10x + 7y = 200; (5,0)表示第二個表達式,省略一個有序對,因爲它違反了x≥0條件(儘管分別將它附加到x,y),(42,0),(0,42)表示最終表達式。

如何將這些表達式中的每一個轉換爲用matplotlib打印的自己的行?我已經考慮創建一個新的列表,line [],每次通過findxy()都會將x,y附加到第[n + 1]行,但我不確定這是否是一個好方法。

回答

0

matplotlib的一個很棒的功能是它的函數集成 - 你可以直接將你的公式應用到plot函數中的numpy數組中。

import numpy as np 
from matplotlib import pyplot 

def funcfunc(a,b,c): 
    x = np.linspace(-10, 10, 100) 
    for pos, val in enumerate(a): 
     cox, coy, coz = val, b[pos], c[pos] 
     pyplot.plot(x, (coz-cox*x)/coy) 
    pyplot.show() 

此函數將生成一個圖形,在-10和10之間的行(在x軸上)。

1

使用numpy的:

import numpy as np 
import matplotlib.pyplot as plt 

x = np.linspace(0,10,100) 

a = [10,11,1] 
b = [7,-8,1] 
c = [200,63,42] 

#ax + by = c 
# y = (c - ax)/b 
for (ai,bi,ci) in zip(a,b,c): 
    y = (1.0*ci - ai*x)/bi #multiply by 1.0 to get floats. 

    plt.plot(x,y, label="{a}x + {b}y = {c}".format(a=ai, b=bi, c=ci)) 

plt.legend() 
plt.show() 

版本使用的次要情節:

import numpy as np 
import matplotlib.pyplot as plt 
from math import ceil, sqrt 

x = np.linspace(0,10,100) 

a = [10,11,1] 
b = [7,-8,1] 
c = [200,63,42] 

nPlots = len(a) 
gridSize = int(ceil(sqrt(nPlots))) 

fig, ax = plt.subplots(gridSize, gridSize) 

#ax + by = c 
# y = (c - ax)/b 
for i, (ai,bi,ci) in enumerate(zip(a,b,c)): 
    y = (1.0*ci - ai*x)/bi #multiply by 1.0 to get floats. 

    ax.flat[i].plot(x,y, label="{a}x + {b}y = {c}".format(a=ai, b=bi, c=ci)) 
    ax.flat[i].legend(loc=0) 

#clear empty plots if not enough to fill the whole grid. 
for j in ax.flat[i+1:]: 
    j.axis('off') 

plt.show() 
+1

+1。我認爲這個答案可以通過使用'plt.subplots'來創建'figure'和'axes'對象,然後直接對'axes'對象進行繪圖來改善。 –

+0

@PaulH是的,這將是一個好主意。我用線條的參數添加了一個圖例。我也可以使用subplots添加一個版本。 – M4rtini

+0

這第一個工作得很好,但如果y =(1.0 * ci - ai * x)/ bi我怎樣才能設置網格只顯示y = np.linspace(0,10,100)而不改變線? –