.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "intro/scipy/auto_examples/plot_curve_fit.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_intro_scipy_auto_examples_plot_curve_fit.py: =============== Curve fitting =============== Demos a simple curve fitting .. GENERATED FROM PYTHON SOURCE LINES 10-11 First generate some data .. GENERATED FROM PYTHON SOURCE LINES 11-26 .. code-block:: default import numpy as np # Seed the random number generator for reproducibility np.random.seed(0) x_data = np.linspace(-5, 5, num=50) noise = 0.01 * np.cos(100 * x_data) a, b = 2.9, 1.5 y_data = a * np.cos(b * x_data) + noise # And plot it import matplotlib.pyplot as plt plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data) .. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_001.png :alt: plot curve fit :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none .. GENERATED FROM PYTHON SOURCE LINES 27-28 Now fit a simple sine function to the data .. GENERATED FROM PYTHON SOURCE LINES 28-38 .. code-block:: default import scipy as sp def test_func(x, a, b, c): return a * np.sin(b * x + c) params, params_covariance = sp.optimize.curve_fit(test_func, x_data, y_data, p0=[2, 1, 3]) print(params) .. rst-class:: sphx-glr-script-out .. code-block:: none [2.900026 1.50012043 1.57079633] .. GENERATED FROM PYTHON SOURCE LINES 39-40 And plot the resulting curve on the data .. GENERATED FROM PYTHON SOURCE LINES 40-49 .. code-block:: default plt.figure(figsize=(6, 4)) plt.scatter(x_data, y_data, label='Data') plt.plot(x_data, test_func(x_data, *params), label='Fitted function') plt.legend(loc='best') plt.show() .. image-sg:: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_002.png :alt: plot curve fit :srcset: /intro/scipy/auto_examples/images/sphx_glr_plot_curve_fit_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.100 seconds) .. _sphx_glr_download_intro_scipy_auto_examples_plot_curve_fit.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_curve_fit.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_curve_fit.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_