使用matplotlib从两个列表中绘制多行

时间:2014-02-11 15:03:34

标签: python regex matplotlib plot lines

在下面的代码中,a,b,c表示三个表达式:10x + 7y = 200,11x-8y = 63,x + y = 42。我想绘制这些表达式中的每一个,我不确定最好的方法是什么。

当我得到以下代码时:

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进行打印?我考虑创建一个新的列表,行[],每个通过findxy()会将x,y附加到行[n + 1],但我不确定这是否是一个好方法。

2 个答案:

答案 0 :(得分: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 :(得分:0)

matplotlib的一大优点是它的功能集成 - 您可以直接将您的公式应用于绘图函数中的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轴上)。