Sparklines are small unlabeled plots, used to visually convey an idea in a small space. This script creates sparklines in a Pandas DataFrame which can then be displayed inline in a Jupyter Notebook or output to an HTML file. It does not annotate the figure, other columns of the DataFrame can be used to convey details about the sparklines.
Background: https://en.wikipedia.org/wiki/Sparkline
Forked and extended from: https://github.com/iiSeymour/sparkline-nb
In [1]:
import numpy as np
import pandas as pd
from scipy import stats
import matplotlib.pyplot as plt
%matplotlib inline
import sparklines
In [2]:
density_func = 78
mean, var, skew, kurt = stats.chi.stats(density_func, moments='mvsk')
x_chi = np.linspace(stats.chi.ppf(0.01, density_func),
stats.chi.ppf(0.99, density_func), 100)
y_chi = stats.chi.pdf(x_chi, density_func)
x_expon = np.linspace(stats.expon.ppf(0.01), stats.expon.ppf(0.99), 100)
y_expon = stats.expon.pdf(x_expon)
a_gamma = 1.99
x_gamma = np.linspace(stats.gamma.ppf(0.01, a_gamma),
stats.gamma.ppf(0.99, a_gamma), 100)
y_gamma = stats.gamma.pdf(x_gamma, a_gamma)
In [3]:
n = 100
In [4]:
np.random.seed(0) # keep generated data the same for git commit
In [5]:
data = [np.random.rand(n),
np.random.randn(n),
np.random.beta(2, 1, size=n),
np.random.binomial(3.4, 0.22, size=n),
np.random.exponential(size=n),
np.random.geometric(0.5, size=n),
np.random.laplace(size=n),
y_chi,
y_expon,
y_gamma]
In [6]:
function = ['rand',
'randn',
'beta',
'binomial',
'exponential',
'geometric',
'laplace',
'chi',
'expon',
'gamma']
In [7]:
df = pd.DataFrame(data)
df['function'] = function
In [8]:
df
Out[8]:
Note: data must be row wise
In [9]:
a = df.ix[:, 0:100]
In [10]:
df_out = pd.DataFrame()
df_out['sparkline'] = sparklines.create(data=a)
sparklines.show(df_out[['sparkline']])
In [11]:
df['sparkline'] = sparklines.create(data=a)
sparklines.show(df[['function', 'sparkline']])
In [12]:
df_out = pd.DataFrame()
df_out['sparkline'] = sparklines.create(data=a,
color='#1b470a',
fill_color='#99a894',
fill_alpha=0.2,
point_color='blue',
point_fill='none',
point_marker='*',
point_size=3,
figsize=(6, 0.25))
sparklines.show(df_out[['sparkline']])
In [13]:
df_copy = df[['function', 'sparkline']].copy()
In [14]:
df_copy['value'] = df.ix[:, 100]
In [15]:
df_copy['change'] = df.ix[:,98] - df.ix[:,99]
In [16]:
df_copy['change_%'] = df_copy.change / df.ix[:,99]
In [17]:
sparklines.show(df_copy)
Inline Jupyter Notebook
In [18]:
sparklines.to_html(df_copy, 'pandas_sparklines_demo')
HTML text for rendering elsewhere
In [19]:
html = sparklines.to_html(df_copy)