Numerical Integration in Python/v3

Learn how to integrate a sequence or list of values numerically


Note: this page is part of the documentation for version 3 of Plotly.py, which is not the most recent version.
See our Version 4 Migration Guide for information about how to upgrade.

New to Plotly?

Plotly's Python library is free and open source! Get started by dowloading the client and reading the primer.
You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

Imports

The tutorial below imports NumPy, Pandas, and SciPy.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import numpy as np
import pandas as pd
import scipy

Integrate the Sine Function

How to use numerical integration to find the area of $y = sin(x)$ between $0$ and $2\pi$.

In [2]:
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)

trace1 = go.Scatter(
    x=x,
    y=y,
    mode='lines',
)

# use numpy's built in trapezoid-rule integration tool
dy = np.trapz(y, x)

annotation = go.Annotation(
    x=4.5,
    y=1.25,
    text='Numerical Integration of sin(x) is approximately %s' % (dy),
    showarrow=False
)

layout = go.Layout(
    annotations=[annotation]
)

trace_data = [trace1]
fig = go.Figure(data=trace_data, layout=layout)

py.iplot(fig, filename='1d-numerical-integration')
Out[2]: