2

I have two arrays, x and y. I want to create a natural cubic spline for the arrays.

I can't figure out how to exactly plot the graph for the spline.

import numpy as np
from scipy.interpolate import CubicSpline

# Calculate 5 natural cubic spline polynomials for 6 points.
# (x,y) = (0,12) (1,14) (2,22) (3,39) (4,58) (5,77)
x = np.array([0,  1,  2,  3,  4,  5 ])
y = np.array([12, 14, 22, 39, 58, 77])

# Calculate natural cubic spline polynomials.
cs = CubicSpline(x, y, bc_type='natural')

Matt Hall
  • 7,614
  • 1
  • 23
  • 36
STEMQs
  • 75
  • 1
  • 10
  • You likely want to evaluate the spline over some points, somewhat like this: ` X = np.arange(0,100,100) matplotlib.pyplot.plot(X, evaluation_of_cs_at(X)) ` – Thomas Lang Oct 07 '19 at 17:34
  • Did you take a look at this post on the forum? https://stackoverflow.com/questions/30039260/how-to-draw-cubic-spline-in-matplotlib – Matthi9000 Oct 07 '19 at 17:37

2 Answers2

0

You can use matplotlib to plot the cubic spline evaluated over the region you're interested in

import matplotlib.pyplot as plt

X = np.linspace(-1, 7, 100)
Y = cs(X)
plt.plot(X, Y)
plt.show()
Kyle Safran
  • 463
  • 3
  • 8
0

You need to make a set of points at which to evaluate the new function.

import matplotlib.pyplot as plt

# x's at which to evaluate.
xs = np.arange(-1, 10, 0.1)

# Plot data with spline.
plt.plot(x, y, 'o')
plt.plot(xs, cs(xs))

This results in:

enter image description here

Matt Hall
  • 7,614
  • 1
  • 23
  • 36