ggplot¶%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.0)
cp = sns.color_palette()
from ggplot import *
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))
g = ggplot(ts, aes(x='dt', y='value', color='kind')) + \
geom_line(size=2.0) + \
xlab('Date') + \
ylab('Value') + \
ggtitle('Random Timeseries')
g
df = pd.read_csv('data/iris.csv')
df.head()
g = ggplot(df, aes(x='petalLength',
y='petalWidth',
color='species')) + \
geom_point(size=40.0) + \
ggtitle('Petal Width v. Length -- by Species')
g
fig, ax = plt.subplots(2, 2, figsize=(10, 10))
g = ggplot(ts, aes(x='dt', y='value', color='kind')) + \
geom_line(size=2.0) + \
facet_wrap(x='kind', ncol=2) + \
ggtitle('Random Timeseries')
g
g = ggplot(df, aes(x='petalLength',
y='petalWidth',
color='species')) + \
facet_grid(y='species') + \
geom_point(size=40.0)
g
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()
g = ggplot(df, aes(x='petalLength',
y='petalWidth',
color='species')) + \
facet_grid(x='random_factor', y='species') + \
geom_point(size=40.0)
g
g = ggplot(df, aes(x='species',
y='petalWidth',
fill='species')) + \
geom_boxplot() + \
ggtitle('Distribution of Petal Width by Species')
g
g = ggplot(df, aes(x='petalWidth',
fill='species')) + \
geom_histogram() + \
ylab('Frequency') + \
ggtitle('Distribution of Petal Width by Species')
g
df = pd.read_csv('data/titanic.csv')
df.head()
dfg = df.groupby(['survived', 'pclass']).agg({'fare': 'mean'})
dfg
g = ggplot(df, aes(x='class', y='fare')) + \
geom_bar()
g
g = ggplot(df, aes(x='class', weight='fare')) + \
geom_bar()
g
df.groupby(['class', 'survived']).\
agg({'fare': 'mean'}).\
reset_index()
g = ggplot(df.groupby(['class', 'survived']).\
agg({'fare': 'mean'}).\
reset_index(), aes(x='class',
fill='factor(survived)',
weight='fare',
y='fare')) + \
geom_bar() + \
ylab('Avg. Fare') + \
xlab('Class') + \
ggtitle('Fare by survival and class')
g
# # in R, I believe you'd do something like this:
ggplot(df, aes(x=factor(survived), y=fare)) +
stat_summary_bin(aes(fill=factor(survived)),
fun.y="mean",
geom="bar") +
facet_wrap(~class)
# # damn ggplot2 is awesome...