Basic Statistics in Python/v3

Learn how to perform basic statistical operations using Python.


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

Import Data

Let us import a dataset to perform our statistics. We will be looking at the consumption of alcohol by country in 2010.

In [2]:
data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/2010_alcohol_consumption_by_country.csv')
df = data[0:10]

table = FF.create_table(df)
py.iplot(table, filename='alcohol-data-sample')
Out[2]:

Mean and Variance

Two of the most basic statistical operations are the mean $\mu$ and standard deviation $\sigma$ of a one-dimension array of data, that is, a sequence of numeric values. The mean of a set of numbers $x_1, ..., x_N$ is defined as:

$$\begin{align*} \mu = \sum_{i=1}^N{x_i} \end{align*} $$

The mean is used colloquially as the average of a set of values. The standard deviation on the other hand is a statistical metric that describes the spread of the data, or how far the values are from the mean. The standard deviation of a set of data is defined as:

$$\begin{align*} \sigma = \sqrt{\frac{1}{N-1}\sum_{i=1}^{N}{(x_i-\mu)^2}} \end{align*} $$
In [3]:
mean = np.mean(data['alcohol'])
st_dev = np.std(data['alcohol'])

print("The mean is %r") %(mean)
print("The standard deviation is %r") %(st_dev)
The mean is 6.2083769633507835
The standard deviation is 4.130671000635401

Secondary Statistics

We can also compute other statistics such as the median, maximum and minimum of the data

In [4]:
median = np.median(data['alcohol'])
maximum = np.max(data['alcohol'])
minimum = np.min(data['alcohol'])

print("The median is %r") %(median)
print("The maximum is %r") %(maximum)
print("The minimum is %r") %(minimum)
The median is 6.4000000000000004
The maximum is 17.5
The minimum is 0.10000000000000001

Visualize the Statistics

We can visualize these statistics by producing a Plotly box or Violin chart.

In [5]:
y = data['alcohol'].values.tolist()

fig = FF.create_violin(y, title='Violin Plot', colors='#604d9e')
py.iplot(fig, filename='alcohol-violin-visual')
Out[5]:
In [6]:
y = data['alcohol'].values.tolist()

trace = go.Box(
    y=y,
    name = 'Box Plot',
    boxpoints='all',
    jitter=0.3,
    marker = dict(
        color = 'rgb(214,12,140)',
    ),
)

layout = go.Layout(
    width=500,
    yaxis=dict(
        title='Alcohol Consumption by Country',
        zeroline=False
    ),
)

data = [trace]
fig= go.Figure(data=data, layout=layout)
py.iplot(fig, filename='alcohol-box-plot')
Out[6]: