Eyzuky
Eyzuky

Reputation: 1935

Plotting a polynomial using Matplotlib and coeffiecients

My code is:

import numpy as np
import matplotlib as plt
polyCoeffiecients = [1,2,3,4,5]
plt.plot(PolyCoeffiecients)
plt.show()

The result for this is straight lines that describe the points in 1,2,3,4,5 and the straight lines between them, instead of the polynomial of degree 5 that has 1,2,3,4,5 as its coeffiecients ( P(x) = 1 + 2x + 3x + 4x + 5x)

How am i suppose to plot a polynomial with just its coefficients?

Upvotes: 7

Views: 53277

Answers (4)

moser
moser

Reputation: 446

Eyzuky, see if this is what you want:

import numpy as np
from matplotlib import pyplot as plt

def PolyCoefficients(x, coeffs):
    """ Returns a polynomial for ``x`` values for the ``coeffs`` provided.

    The coefficients must be in ascending order (``x**0`` to ``x**o``).
    """
    o = len(coeffs)
    print(f'# This is a polynomial of order {o}.')
    y = 0
    for i in range(o):
        y += coeffs[i]*x**i
    return y

x = np.linspace(0, 9, 10)
coeffs = [1, 2, 3, 4, 5]
plt.plot(x, PolyCoefficients(x, coeffs))
plt.show()

Upvotes: 12

Max Conradt
Max Conradt

Reputation: 116

Generic, vectorized implementation:

from typing import Sequence, Union
import numpy as np
import matplotlib.pyplot as plt


Number = Union[int, float, complex]

def polyval(coefficients: Sequence[Number], x: Sequence[Number]) -> np.ndarray:
    # expand dimensions to allow broadcasting (constant time + inexpensive)
    # axis=-1 allows for arbitrarily shaped x
    x = np.expand_dims(x, axis=-1)
    powers = x ** np.arange(len(coefficients))
    return powers @ coefficients

def polyplot(coefficients: Sequence[Number], x: Sequence[Number]) -> None:
    y = polyval(coefficients, x)
    plt.plot(x, y)

polyplot(np.array([0, 0, -1]), np.linspace(-10, 10, 210))
plt.show()

Upvotes: 2

charlie1450
charlie1450

Reputation: 111

You could approximately draw the polynomial by getting lots of x-values and using np.polyval() to get the y-values of your polynomial at the x-values. Then you could just plot the x-vals and y-vals.

import numpy as np
import matplotlib.pyplot as plt

curve = np.array([1,2,3,4,5])
x = np.linspace(0,10,100)
y = [np.polyval(curve, i) for i in x]
plt.plot(x,y)

Upvotes: 11

dani_bandita
dani_bandita

Reputation: 93

A very pythonic solution is to use list comprehension to calculate the values for the function.

import numpy as np
from matplotlib import pyplot as plt

x = np.linspace(0, 10, 11)
coeffs = [1, 2, 3, 4, 5]
y = np.array([np.sum(np.array([coeffs[i]*(j**i) for i in range(len(coeffs))])) for j in x])
plt.plot(x, y)
plt.show()

Upvotes: 2

Related Questions