Visualizing with the ggplot


In [1]:
%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()
In [2]:
from ggplot import *


Thing 1: Line Chart (with many lines)


In [3]:
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()
Out[3]:
dt kind value
0 2000-01-01 A 1.442521
1 2000-01-02 A 1.981290
2 2000-01-03 A 1.586494
3 2000-01-04 A 1.378969
4 2000-01-05 A -0.277937
In [4]:
# in matplotlib-land, the notion of a "tidy"
# dataframe matters not
dfp = ts.pivot(index='dt', columns='kind', values='value')
dfp.head()
Out[4]:
kind A B C D
dt
2000-01-01 1.442521 1.808741 0.437415 0.096980
2000-01-02 1.981290 2.277020 0.706127 -1.523108
2000-01-03 1.586494 3.474392 1.358063 -3.100735
2000-01-04 1.378969 2.906132 0.262223 -2.660599
2000-01-05 -0.277937 3.489553 0.796743 -3.417402
In [5]:
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
Out[5]:
<ggplot: (292881197)>


Thing 2: Scatter


In [6]:
df = pd.read_csv('data/iris.csv')
df.head()
Out[6]:
petalLength petalWidth sepalLength sepalWidth species
0 1.4 0.2 5.1 3.5 setosa
1 1.4 0.2 4.9 3.0 setosa
2 1.3 0.2 4.7 3.2 setosa
3 1.5 0.2 4.6 3.1 setosa
4 1.4 0.2 5.0 3.6 setosa
In [7]:
g = ggplot(df, aes(x='petalLength',
                   y='petalWidth',
                   color='species')) + \
        geom_point(size=40.0) + \
        ggtitle('Petal Width v. Length -- by Species')
g
Out[7]:
<ggplot: (292793009)>


Thing 3: Trellising the Above


In [8]:
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
Out[8]:
<ggplot: (293604941)>
In [9]:
g = ggplot(df, aes(x='petalLength',
                   y='petalWidth',
                   color='species')) + \
        facet_grid(y='species') + \
        geom_point(size=40.0)
g
Out[9]:
<ggplot: (292477601)>
In [10]:
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()
Out[10]:
petalLength petalWidth sepalLength sepalWidth species random_factor
0 1.4 0.2 5.1 3.5 setosa B
1 1.4 0.2 4.9 3.0 setosa B
2 1.3 0.2 4.7 3.2 setosa B
3 1.5 0.2 4.6 3.1 setosa B
4 1.4 0.2 5.0 3.6 setosa B
In [11]:
g = ggplot(df, aes(x='petalLength',
                   y='petalWidth',
                   color='species')) + \
        facet_grid(x='random_factor', y='species') + \
        geom_point(size=40.0)
g
Out[11]:
<ggplot: (292764069)>


Thing 4: Visualizing Distributions (Boxplot and Histogram)


In [12]:
g = ggplot(df, aes(x='species',
                   y='petalWidth',
                   fill='species')) + \
        geom_boxplot() + \
        ggtitle('Distribution of Petal Width by Species')
g
Out[12]:
<ggplot: (298989465)>
In [13]:
g = ggplot(df, aes(x='petalWidth',
                   fill='species')) + \
        geom_histogram() + \
        ylab('Frequency') + \
        ggtitle('Distribution of Petal Width by Species')
g
Out[13]:
<ggplot: (298304285)>


Thing 5: Bar Chart


In [14]:
df = pd.read_csv('data/titanic.csv')
df.head()
Out[14]:
survived pclass sex age sibsp parch fare embarked class who adult_male deck embark_town alive alone
0 0 3 male 22.0 1 0 7.2500 S Third man True NaN Southampton no False
1 1 1 female 38.0 1 0 71.2833 C First woman False C Cherbourg yes False
2 1 3 female 26.0 0 0 7.9250 S Third woman False NaN Southampton yes True
3 1 1 female 35.0 1 0 53.1000 S First woman False C Southampton yes False
4 0 3 male 35.0 0 0 8.0500 S Third man True NaN Southampton no True
In [15]:
dfg = df.groupby(['survived', 'pclass']).agg({'fare': 'mean'})
dfg
Out[15]:
fare
survived pclass
0 1 64.684008
2 19.412328
3 13.669364
1 1 95.608029
2 22.055700
3 13.694887
In [16]:
g = ggplot(df, aes(x='class', y='fare')) + \
        geom_bar()
g
Out[16]:
<ggplot: (300387777)>
In [30]:
g = ggplot(df, aes(x='class', weight='fare')) + \
        geom_bar()
g
Out[30]:
<ggplot: (303714189)>
In [33]:
df.groupby(['class', 'survived']).\
               agg({'fare': 'mean'}).\
               reset_index()
Out[33]:
class survived fare
0 First 0 64.684008
1 First 1 95.608029
2 Second 0 19.412328
3 Second 1 22.055700
4 Third 0 13.669364
5 Third 1 13.694887
In [42]:
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
Out[42]:
<ggplot: (305511413)>
In [35]:
# # 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...