Faceted grid in Seaborn

Up until now, we have already mentioned FacetGrid a few times, but what exactly is it?

As you may know, FacetGrid is an engine for subsetting data and drawing plot panels determined by assigning variables to the rows and columns of hue parameters. While we can use wrapper functions such as lmplot and factorplot to scaffold plots on FacetGrid easily, it would be more flexible to build FacetGrid from scratch. To do that, we first supply a pandas DataFrame to the FacetGrid object and specify the way to lay out the grid via col, row, and hue parameters. Then we can assign a Seaborn or Matplotlib plotting function to each panel by calling the map() function of the FacetGrid object:

# Create a FacetGrid
g = sns.FacetGrid(stock_df, col="Company", hue="Company",
size=3, aspect=2, col_wrap=2)

# Map the seaborn.distplot function to the panels,
# which shows a histogram of closing prices.
g.map(sns.distplot, "Close")

# Label the axes
g.set_axis_labels("Closing price (US Dollars)", "Density")

plt.show()

We can also supply keyword arguments to the plotting functions:

g = sns.FacetGrid(stock_df, col="Company", hue="Company",
size=3, aspect=2.2, col_wrap=2)

# We can supply extra kwargs to the plotting function.
# Let's turn off KDE line (kde=False), and plot raw
# frequency of bins only (norm_hist=False).
# By setting rug=True, tick marks that denotes the
# density of data points will be shown in the bottom.
g.map(sns.distplot, "Close", kde=False, norm_hist=False, rug=True)

g.set_axis_labels("Closing price (US Dollars)", "Density")

plt.show()

FacetGrid is not limited to the use of Seaborn plotting functions; let's try to map the good old Matplotlib.pyplot.plot() function to FacetGrid:

from matplotlib.dates import DateFormatter


g = sns.FacetGrid(stock_df, hue="Company", col="Industry",
size=4, aspect=1.5, col_wrap=2)

# plt.plot doesn't support string-formatted Date,
# so we need to use the Datetime column that we
# prepared earlier instead.
g.map(plt.plot, "Datetime", "Close", marker="o", markersize=3, linewidth=1)
g.add_legend()

# We can access individual axes through g.axes[column]
# or g.axes[row,column] if multiple rows are present.
# Let's adjust the tick formatter and rotate the tick labels
# in each axes.
for col in range(2):
g.axes[col].xaxis.set_major_formatter(DateFormatter('%Y-%m-%d'))
plt.setp(g.axes[col].get_xticklabels(), rotation=30)

g.set_axis_labels("", "Closing price (US Dollars)")
plt.show()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset