pandas¶%matplotlib inline
# standard
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
# I've got style,
# miles and miles
import seaborn as sns
sns.set()
sns.set_context('notebook', font_scale=1.5)
cp = sns.color_palette()
ts = pd.read_csv('data/ts.csv')
# casting to datetime is important for
# ensuring plots "just work"
ts = ts.assign(dt = pd.to_datetime(ts.dt))
ts.head()
# in matplotlib-land, the notion of a "tidy"
# dataframe matters not
dfp = ts.pivot(index='dt', columns='kind', values='value')
dfp.head()
fig, ax = plt.subplots(1, 1,
figsize=(7.5, 5))
dfp.plot(ax=ax)
ax.set(xlabel='Date',
ylabel='Value',
title='Random Timeseries')
ax.legend(loc=2)
fig.autofmt_xdate()
df = pd.read_csv('data/iris.csv')
df.head()
fig, ax = plt.subplots(1, 1, figsize=(7.5, 7.5))
for i, s in enumerate(df.species.unique()):
df[df.species == s].plot.scatter(
'petalLength', 'petalWidth',
c=cp[i], label=s, ax=ax
)
ax.set(xlabel='Petal Length',
ylabel='Petal Width',
title='Petal Width v. Length -- by Species')
ax.legend(loc=2)
dfp.plot(subplots=True, layout=(2, 2), figsize=(10, 10),
title='Random Timeseries -- Value over Time')
tmp_n = df.shape[0] - df.shape[0]/2
df['random_factor'] = np.random.permutation(['A'] * tmp_n + ['B'] * (df.shape[0] - tmp_n))
df.head()
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
df.boxplot(column='petalWidth', by='species', ax=ax)
sns.set_context('notebook', font_scale=1.25)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
df.boxplot(column='petalWidth', by=['species', 'random_factor'], ax=ax)
sns.set_context('notebook', font_scale=1.5)
fig, ax = plt.subplots(1, 1, figsize=(10, 10))
df.hist(column='petalWidth', by='species', grid=None, ax=ax)
df = pd.read_csv('data/titanic.csv')
df.head()
dfg = df.groupby(['survived', 'pclass']).agg({'fare': 'mean'})
dfg
fig, ax = plt.subplots(1, 1, figsize=(12.5, 7))
dfg.reset_index().\
pivot(index='pclass',
columns='survived',
values='fare').plot.bar(ax=ax)
ax.set(xlabel='Class',
ylabel='Fare',
title='Fare by survival and class')