【问题标题】:Matplotlib - Plot multiple lines on the same chart [duplicate]Matplotlib - 在同一个图表上绘制多条线[重复]
【发布时间】:2017-02-24 07:47:33
【问题描述】:

这方面的信息令人惊讶地难以找到。我有两个函数要一起绘制,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)

【问题讨论】:

    标签: python numpy matplotlib plot regression


    【解决方案1】:

    在绘图中添加一条线:

    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 轴进行绘图。

    您将要在同一函数内或在函数外绘制两组数据。否则,您也会遇到本地与全球问题。

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2011-05-02
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 2020-03-02
      • 2020-05-06
      • 2013-06-13
      • 1970-01-01
      相关资源
      最近更新 更多