Basic Statistics in Python/v3
Learn how to perform basic statistical operations using Python.
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!
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.
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')
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:
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:
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)
Secondary Statistics¶
We can also compute other statistics such as the median
, maximum
and minimum
of the data
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)
Visualize the Statistics¶
We can visualize these statistics by producing a Plotly box or Violin chart.
y = data['alcohol'].values.tolist()
fig = FF.create_violin(y, title='Violin Plot', colors='#604d9e')
py.iplot(fig, filename='alcohol-violin-visual')
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')