Basic Python Programming USE NUMPY PLEASE Define a function

Basic Python Programming USE NUMPY PLEASE

Define a function plot_multiple_polynomials( xs, ys, degree, colors ) that takes in two lists of coordinates, a degree, and a list of strings representing plot colors.

This function should:

Plot the given xs and ys with colors[0] and a label.

For every degree from zero to degree:

Call polynomial_fit( xs, ys, degree ) to get fitted_ys.

Plot fitted_ys on xs with colors[degree+1] and a label.

Label every plotted line and generate a legend.

def polynomial_fit(xs, ys, degree):
return(np.poly1d(np.polyfit(np.array(xs), np.array(ys), degree))(xs))

Example Usage:
>>> xs = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
>>> ys = [ 4, 7, 12, 16, 10, 10, 9, 15, 17, 19, 10, 8, 6, 5, 2, 1]
>>> plot_multiple_polynomials(xs, ys, 5, [\'mo\',\'y--\',\'g--\',\'k--\',\'r--\',\'b--\',\'m\'])
>>> plt.show()

Solution

import numpy as np import matplotlib.pyplot as plt def polynomial_fit(xs, ys, degree): return np.poly1d(np.polyfit(np.array(xs), np.array(ys), degree))(xs) def plot_multiple_polynomials(xs, ys, degree, colors): for degree in range(degree + 1): fitted_ys = polynomial_fit(xs, ys, degree) plt.plot(xs, fitted_ys, colors[degree + 1], label=\'line \' + str(degree + 1)) plt.legend(loc=1) xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] ys = [4, 7, 12, 16, 10, 10, 9, 15, 17, 19, 10, 8, 6, 5, 2, 1] plot_multiple_polynomials(xs, ys, 5, [\'mo\', \'y--\', \'g--\', \'k--\', \'r--\', \'b--\', \'m\']) plt.show()
Basic Python Programming USE NUMPY PLEASE Define a function plot_multiple_polynomials( xs, ys, degree, colors ) that takes in two lists of coordinates, a degree

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site