seaborn.jointplot


Seaborn's jointplot displays a relationship between 2 variables (bivariate) as well as 1D profiles (univariate) in the margins. This plot is a convenience class that wraps JointGrid.


In [2]:
%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
plt.rcParams['figure.figsize'] = (20.0, 10.0)
plt.rcParams['font.family'] = "serif"

The multivariate normal distribution is a nice tool to demonstrate this type of plot as it is sampling from a multidimensional Gaussian and there is natural clustering. I'll set the covariance matrix equal to the identity so that the X and Y variables are uncorrelated -- meaning we will just get a blob


In [10]:
# Generate some random multivariate data
x, y = np.random.RandomState(8).multivariate_normal([0, 0], [(1, 0), (0, 1)], 1000).T
df = pd.DataFrame({"x":x,"y":y})

Default plot


In [11]:
p = sns.jointplot(data=df,x='x', y='y')


Currently, jointplot wraps JointGrid with the following options for kind:

- scatter
- reg
- resid 
- kde 
- hex 

Scatter is the default parameters


In [12]:
p = sns.jointplot(data=df,x='x', y='y',kind='scatter')


'reg' plots a linear regression line. Here the line is close to flat because we chose our variables to be uncorrelated


In [13]:
p = sns.jointplot(data=df,x='x', y='y',kind='reg')


'resid' plots the residual of the data to the regression line -- which is not very useful for this specific example because our regression line is almost flat and thus the residual is almost the same as the data.


In [14]:
x2, y2 = np.random.RandomState(9).multivariate_normal([0, 0], [(1, 0), (0, 1)], len(x)).T
df2 = pd.DataFrame({"x":x,"y":y2})

p = sns.jointplot(data=df,x='x', y='y',kind='resid')


kde plots a kernel density estimate in the margins and converts the interior into a shaded countour plot


In [15]:
p = sns.jointplot(data=df,x='x', y='y',kind='kde')


'hex' bins the data into hexagons with histograms in the margins. At this point you probably see the "pre-cooked" nature of jointplot. It provides nice defaults, but if you wanted, for example, a KDE on the margin of this hexplot you will need to use JointGrid.


In [16]:
p = sns.jointplot(data=df,x='x', y='y',kind='hex')


stat_func can be used to provide a function for computing a summary statistic from the data. The full x, y data vectors are passed in, so the function must provide one value or a tuple from many. As an example, I'll provide tmin, which when used in this way will return the smallest value of x that was greater than its corresponding value of y.


In [17]:
from scipy.stats import tmin
p = sns.jointplot(data=df, x='x', y='y',kind='kde',stat_func=tmin)

# tmin is computing roughly the equivalent of the following
print(df.loc[df.x>df.y,'x'].min())


-1.37265900987

Change the color


In [26]:
p = sns.jointplot(data=df,
                  x='x',
                  y='y',
                  kind='kde',
                  color="#99ffff")


`ratio` adjusts the relative size of the marginal plots and 2D distribution

In [33]:
p = sns.jointplot(data=df,
                  x='x',
                  y='y',
                  kind='kde',
                  ratio=1)


Create separation between 2D plot and marginal plots with space


In [50]:
p = sns.jointplot(data=df,
                  x='x',
                  y='y',
                  kind='kde',
                  space=2)


xlim and ylim can be used to adjust the field of view


In [54]:
p = sns.jointplot(data=df,
                  x='x',
                  y='y',
                  kind='kde',
                  xlim=(-15,15),
                  ylim=(-15,15))


Pass additional parameters to the marginal plots with marginal_kws. You can pass similar options to joint_kws and annot_kws


In [87]:
p = sns.jointplot(data=df,
                  x='x',
                  y='y',
                  kind='kde',
                  marginal_kws={'lw':5,
                                'color':'red'})


Finalize


In [132]:
from itertools import chain
p = sns.jointplot(data=df,
                  x='x',
                  y='y',
                  kind='kde',
                  xlim=(-3,3),
                  ylim=(-3,3),
                  marginal_kws={'lw':3}).set_axis_labels('X','Y')
p.ax_marg_x.set_facecolor('#ccffcc')
p.ax_marg_y.set_facecolor('#ccffcc')
for l in chain(p.ax_marg_x.axes.lines,p.ax_marg_y.axes.lines):
    l.set_linestyle('--')
    l.set_color('black')



In [111]:
[d for d in dir(p.ax_marg_x.axes) if "line" in d]


Out[111]:
['_get_lines',
 '_update_line_limits',
 'add_line',
 'axhline',
 'axvline',
 'get_lines',
 'get_xgridlines',
 'get_xticklines',
 'get_ygridlines',
 'get_yticklines',
 'hlines',
 'lines',
 'vlines']

In [115]:
for l in p.ax_marg_x.axes.lines:
    print(dir(l))


['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_agg_filter', '_alpha', '_animated', '_antialiased', '_axes', '_clipon', '_clippath', '_color', '_contains', '_dashOffset', '_dashSeq', '_dashcapstyle', '_dashjoinstyle', '_drawStyles_l', '_drawStyles_s', '_draw_dash_dot', '_draw_dashed', '_draw_dotted', '_draw_lines', '_draw_solid', '_draw_steps_mid', '_draw_steps_post', '_draw_steps_pre', '_drawstyle', '_get_markerfacecolor', '_get_rgba_face', '_get_rgba_ln_color', '_get_transformed_path', '_gid', '_invalidx', '_invalidy', '_is_sorted', '_label', '_lineFunc', '_lineStyles', '_linestyle', '_linestyles', '_linewidth', '_marker', '_markeredgecolor', '_markeredgewidth', '_markerfacecolor', '_markerfacecoloralt', '_markersize', '_markevery', '_mouseover', '_oid', '_path', '_path_effects', '_picker', '_prop_order', '_propobservers', '_rasterized', '_remove_method', '_set_gc_clip', '_sketch', '_snap', '_solidcapstyle', '_solidjoinstyle', '_split_drawstyle_linestyle', '_stale', '_sticky_edges', '_subslice', '_transform', '_transformSet', '_transform_path', '_transformed_path', '_url', '_us_dashOffset', '_us_dashSeq', '_visible', '_x', '_x_filled', '_xcid', '_xorig', '_xy', '_y', '_ycid', '_yorig', 'add_callback', 'aname', 'axes', 'clipbox', 'contains', 'convert_xunits', 'convert_yunits', 'draw', 'drawStyleKeys', 'drawStyles', 'eventson', 'figure', 'fillStyles', 'filled_markers', 'findobj', 'format_cursor_data', 'get_aa', 'get_agg_filter', 'get_alpha', 'get_animated', 'get_antialiased', 'get_axes', 'get_c', 'get_children', 'get_clip_box', 'get_clip_on', 'get_clip_path', 'get_color', 'get_contains', 'get_cursor_data', 'get_dash_capstyle', 'get_dash_joinstyle', 'get_data', 'get_drawstyle', 'get_figure', 'get_fillstyle', 'get_gid', 'get_label', 'get_linestyle', 'get_linewidth', 'get_ls', 'get_lw', 'get_marker', 'get_markeredgecolor', 'get_markeredgewidth', 'get_markerfacecolor', 'get_markerfacecoloralt', 'get_markersize', 'get_markevery', 'get_mec', 'get_mew', 'get_mfc', 'get_mfcalt', 'get_ms', 'get_path', 'get_path_effects', 'get_picker', 'get_pickradius', 'get_rasterized', 'get_sketch_params', 'get_snap', 'get_solid_capstyle', 'get_solid_joinstyle', 'get_transform', 'get_transformed_clip_path_and_affine', 'get_url', 'get_visible', 'get_window_extent', 'get_xdata', 'get_xydata', 'get_ydata', 'get_zorder', 'have_units', 'hitlist', 'ind_offset', 'is_dashed', 'is_figure_set', 'is_transform_set', 'lineStyles', 'markers', 'mouseover', 'pchanged', 'pick', 'pickable', 'pickradius', 'properties', 'recache', 'recache_always', 'remove', 'remove_callback', 'set', 'set_aa', 'set_agg_filter', 'set_alpha', 'set_animated', 'set_antialiased', 'set_axes', 'set_c', 'set_clip_box', 'set_clip_on', 'set_clip_path', 'set_color', 'set_contains', 'set_dash_capstyle', 'set_dash_joinstyle', 'set_dashes', 'set_data', 'set_drawstyle', 'set_figure', 'set_fillstyle', 'set_gid', 'set_label', 'set_linestyle', 'set_linewidth', 'set_ls', 'set_lw', 'set_marker', 'set_markeredgecolor', 'set_markeredgewidth', 'set_markerfacecolor', 'set_markerfacecoloralt', 'set_markersize', 'set_markevery', 'set_mec', 'set_mew', 'set_mfc', 'set_mfcalt', 'set_ms', 'set_path_effects', 'set_picker', 'set_pickradius', 'set_rasterized', 'set_sketch_params', 'set_snap', 'set_solid_capstyle', 'set_solid_joinstyle', 'set_transform', 'set_url', 'set_visible', 'set_xdata', 'set_ydata', 'set_zorder', 'stale', 'stale_callback', 'sticky_edges', 'update', 'update_from', 'validCap', 'validJoin', 'verticalOffset', 'zorder']

In [ ]: