Show Sidebar Hide Sidebar

Baseline Subtraction in Python

Learn how to subtract baseline estimates from data in Python.

New to Plotly?

Plotly's Python library is free and open source! Get started by downloading 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, SciPy and PeakUtils.

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

import numpy as np
import pandas as pd
import scipy
import peakutils

Import Data

As with our baseline detection example, we will import some data on milk production by month:

In [2]:
milk_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/monthly-milk-production-pounds.csv')
time_series = milk_data['Monthly milk production (pounds per cow)']
time_series = np.asarray(time_series)

df = milk_data[0:15]

table = FF.create_table(df)
py.iplot(table, filename='milk-production-dataframe')
Out[2]:

Plot with Baseline

To subtact a baseline estimate from our data, it is a good idea to first we must first calculate the baseline values then plot the data with the baseline drawn in.

In [3]:
baseline_values = peakutils.baseline(time_series)

trace = go.Scatter(
    x=[j for j in range(len(time_series))],
    y=time_series,
    mode='lines',
    marker=dict(
        color='#547C66',
    ),
    name='Original Plot'
)

trace2 = go.Scatter(
    x=[j for j in range(len(time_series))],
    y=baseline_values,
    mode='markers',
    marker=dict(
        size=3,
        color='#EB55BF',
        symbol='open-circle'
    ),
    name='Baseline'
)

data = [trace, trace2]
py.iplot(data, filename='milk-production-plot-with-baseline')
Out[3]:

Baseline Subtraction

In [4]:
baseline_values = peakutils.baseline(time_series)

trace1 = go.Scatter(
    x=[j for j in range(len(time_series))],
    y=time_series,
    mode='lines',
    marker=dict(
        color='#547C66',
    ),
    name='Original Plot'
)

trace2 = go.Scatter(
    x=[j for j in range(len(time_series))],
    y=time_series - baseline_values,
    mode='lines',
    marker=dict(
        color='#ACDB86',
    ),
    name='Baseline Subtracted'
)

fig = tools.make_subplots(rows=2, cols=1)

fig.append_trace(trace1, 1, 1)
fig.append_trace(trace2, 2, 1)

fig['layout'].update(height=600, width=800, title='Baseline Subtraction')
py.iplot(fig, filename='milk-production-plot-baseline-subtraction')
This is the format of your plot grid:
[ (1,1) x1,y1 ]
[ (2,1) x2,y2 ]

Out[4]:
Still need help?
Contact Us

For guaranteed 24 hour response turnarounds, upgrade to a Developer Support Plan.