The Python visualization library Seaborn is based on matplotlib and provides a high-level interface for drawing attractive statistical graphics.
Make use of the following aliases to import the libraries:
>>> import matplotlib.pyplot as plt
>>> import seaborn as sns
The basic steps to creating plots with Seaborn are:
- Prepare some data
- Control figure aesthetics
- Plot with Seaborn
- Further customize your plot
>>> import matplotlib.pyplot as plt
>>>> import seaborn as sns
>>> tips = sns.load_dataset("tips") # Step 1
>>>> sns.set_style("whitegrid") # Step 2
>>>> g = sns.lmplot(x="tip", # Step 3
y='total_bill',
data=tips,
aspect=2)
>>> g = (g.set_axis_labels("Tip","Total bill(USD)").
set(xlim=(0,10),ylim=(0,100)))
>>> plt.title("title") # Step 4
>>> plt.show(g) # Step 5
1. Data
>>> import pandas as pd
>>> import numpy as np
>>> uniform_data = np.random.rand(10, 12)
>>> data = pd.DataFrame({'x':np.arange(1,101),
'y':np.random.normal(0,4,100)})
Seaborn also offers built-in data sets:
>>> titanic = sns.load_dataset("titanic")
>>> iris = sns.load_dataset("iris")
2. Figure Aesthetics
# Create a figure and one subplot
>>> f, ax = plt.subplots(figsize=(5,6))
2.1 Seaborn Styles
# (Re)set the seaborn default
>>> sns.set()
# Set the matplotlib parameters
>>> sns.set_style("whitegrid")
# Set the matplotlib parameters
>>> sns.set_style("ticks",
{"xtick.major.size":8, "ytick.major.size":8}))
# Return a dict of params or use with with to temporarily set the style
>>> sns.axes_style("whitegrid")
2.2 Context Functions
# Set context to "talk"
>>> sns.set_context("talk")
# Set context to "notebook", Scale font elements and override param mapping
>>> sns.set_context("notebook",
font_scale=1.5, rc={"lines.linewidth":2.5})
2.3 Color Palette
# Define the color palette
>>> sns.set_palette("husl",3)
# Use with with to temporarily set palette
>>> sns.color_palette("husl")
# Set your own color palette
>>> flatui =["#9b59b6","#3498db","#95a5a6","#e74c3c","#34495e","#2ecc71"]
>>> sns.set_palette(flatui)
3. Plotting with Seaborn
3.1 Axis Grids
# Subplot grid for plotting conditional relationships
>>> g = sns.FacetGrid(titanic,
col="survived",
row="sex")
>>> g = g.map(plt.hist,"age")
# Draw a categorical plot onto a Facetgrid
>>> sns.factorplot(x="pclass",
y="survived",
hue="sex",
data=titanic)
# Plot data and regression model fits across a FacetGrid
>>> sns.lmplot(x="sepal_width",
y="sepal_length",
hue="species",
data=iris)
# Subplot grid for plotting pairwise relationships
>>> h = sns.PairGrid(iris)
>>> h = h.map(plt.scatter)
# Plot pairwise bivariate distributions
>>> sns.pairplot(iris)
# Grid for bivariate plot with marginal univariate plots
>>> i = sns.JointGrid(x="x",
y="y",
data=data)
>>> i = i.plot(sns.regplot,
sns.distplot)
# Plot bivariate distribution
>>> sns.jointplot("sepal_length",
"sepal_width",
data=iris,
kind='kde')