Matplotlib - 在同一张图表上绘制多条线

Matplotlib - Plot multiple lines on the same chart

这方面的信息出奇地难以找到。我有两个函数要一起绘制,enumeration()betterEnumeration()

import matplotlib.pyplot as plt
import time
import numpy as np
import sympy
from sympy import S, symbols
import random
from math import floor

def enumeration(array):
    max = None
    to_return = (max, 0, 0)
    for i in range(0, len(array) + 1):
        for j in range(0, i):
            currentSum = 0
            for k in range(j, i):
                currentSum += array[k]
                if (max is None) or (currentSum > max):
                    max = currentSum
                    to_return = (max, j, k) 
    return to_return

def betterEnumeration(array):
    max = None
    to_return = (max, 0, 0)
    for i in range(1, len(array) + 1):
        currentSum = 0
        for j in range(i, len(array) + 1):
            currentSum += array[j - 1]
            if (max is None) or (currentSum > max):
                max = currentSum        
                to_return = (max, i-1, j-1)    
    return to_return

我还有两个辅助函数 randomArray()regressionCurve()

def randomArray(totalNumbers,min,max):
    array = []
    while totalNumbers > 0:
        array.append(random.randrange(min,max))
        totalNumbers -= 1
    return array

def regressionCurve(x,y):
    # calculate polynomial
    p = np.polyfit(x, y, 3)
    f = np.poly1d(p)

    # calculate new x's and y's
    x_new = np.linspace(x[0], x[-1], 50)
    y_new = f(x_new)

    x = symbols("x")
    poly = sum(S("{:6.5f}".format(v))*x**i for i, v in enumerate(p[::-1]))
    eq_latex = sympy.printing.latex(poly)

    plt.plot(x_new, y_new, label="${}$".format(eq_latex))
    plt.legend(fontsize="small")
    plt.show()

我想在同一张图表上绘制这两个函数,包括原始数据点和回归曲线。以下代码将绘制 enumeration() 的数据点,然后为它们制作回归曲线,但我不确定如何在同一张图表上同时绘制 enumeration()betterEnumeration()

def chart():
    nValues = [10,25,50,100,250,500,1000]
    avgExecTimes = []
    for n in nValues: # For each n value
        totals = []
        sum = 0
        avgExecTime = 0
        for i in range(0,10): # Create and test 10 random arrays
            executionTimes = []
            array = randomArray(n,0,10)
            t1 = time.clock()
            enumeration(array)
            t2 = time.clock()
            total = t2-t1
            totals.append(total)
            executionTimes.append(total)
            print("Time elapsed(n=" + str(n) + "): " + str(total))
        for t in totals: # Find avg running time for each n's 10 executions
            sum += t
        avgExecTime = sum/10
        avgExecTimes.append(avgExecTime)
        print("Avg execution time: " + str(avgExecTime))

    # Chart execution times
    plt.plot(nValues,avgExecTimes)
    plt.ylabel('Seconds')
    plt.xlabel('n')
    plt.show()

    # Chart curve that fits
    x = np.array(nValues)
    y = np.array(avgExecTimes)
    regressionCurve(x,y)

向图中添加一条线:

plt.plot(x,y)

所以,如果您想绘制 x1、y1,然后添加 x2、y2:

plt.plot(x1,y1)
plt.plot(x2,y2)

但是,这将以默认颜色绘制第二条线。您将要添加一个颜色组件:

plt.plot(x1,y1, c='b')
plt.plot(x2,y2, c= 'g')

如果单位不同,您需要查看 twinx,它允许您使用 2 个不同的 y 轴但相同的 x 轴进行绘图。

您将要绘制同一函数内或函数外的两组数据。否则,您也会 运行 陷入本地与全球问题。