很难找到相关信息。我有两个我想要一起绘制的函数,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)
答案 0 :(得分: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轴。
您将要在同一函数内或在函数外部绘制两组数据。否则,您也遇到了本地问题和全球问题。