Time for action – plotting a polynomial function
To illustrate how plotting works, let's display some polynomial graphs. We will use the NumPy polynomial function poly1d() to create a polynomial.
- Take the standard input values as polynomial coefficients. Use the NumPy
poly1d()function to create a polynomial:func = np.poly1d(np.array([1, 2, 3, 4]).astype(float))
- Create the
xvalues with the NumPy thelinspace()function. Use the range-10to10and create30even spaced values:x = np.linspace(-10, 10, 30)
- Calculate the polynomial values using the polynomial we created in the first step:
y = func(x)
- Call the
plot()function; this does not immediately display the graph:plt.plot(x, y)
- Add a label to the
xaxis with thexlabel()function:plt.xlabel('x') - Add a label to the
yaxis with theylabel()function:plt.ylabel('y(x)') - Call the
show()function to display the graph:plt.show()
The following is a plot with polynomial coefficients 1, 2, 3, and 4:
