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.

  1. 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))
  2. Create the x values with the NumPy linspace function. Use the range -10 to 10 and create 30 even spaced values.
    x = np.linspace(-10, 10, 30)
  3. Calculate the polynomial values using the polynomial that we created in the first step.
    y = func(x)
  4. Call the plot function; this does not immediately display the graph.
    plt.plot(x, y)
  5. Add a label to the x axis with xlabel function.
    plt.xlabel('x’)
  6. Add a label to the y axis with ylabel function.
    plt.ylabel('y(x)’)
  7. Call the show function to display the graph.
    plt.show()

Here is a plot with polynomial coefficients 1, 2, 3, and 4:

Time for action – plotting a polynomial function

What just happened?

We displayed a graph of a polynomial on our screen. We added labels to the x and y axis (see polyplot.py):

import numpy as np
import matplotlib.pyplot as plt

func = np.poly1d(np.array([1, 2, 3, 4]).astype(float))
x = np.linspace(-10, 10, 30)
y = func(x)

plt.plot(x, y)
plt.xlabel('x’)
plt.ylabel('y(x)’)
plt.show()

Pop quiz – the plot function

Q1. What does the plot function do?

  1. It displays two-dimensional plots on screen.
  2. It saves an image of a two-dimensional plot in a file.
  3. It does both 1 and 2.
  4. It does neither 1, 2, or 3.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset