Reputation: 73
I'm trying to create a multi-page pdf using FacetGrid from this (https://seaborn.pydata.org/examples/many_facets.html). There are 20 grids images and I want to save the first 10 grids in the first page of pdf and the second 10 grids to the second page of pdf file. I got the idea of create mutipage pdf file from this (Export huge seaborn chart into pdf with multiple pages). This example works on sns.catplot() but in my case (sns.FacetGrid) the output pdf file has two pages and each page has all of the 20 grids instead of dividing 10 grids in each page.
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Create a dataset with many short random walks
rs = np.random.RandomState(4)
pos = rs.randint(-1, 2, (20, 5)).cumsum(axis=1)
pos -= pos[:, 0, np.newaxis]
step = np.tile(range(5), 20)
walk = np.repeat(range(20), 5)
df = pd.DataFrame(np.c_[pos.flat, step, walk],
columns=["position", "step", "walk"])
# plotting FacetGrid
def grouper(iterable, n, fillvalue=None):
from itertools import zip_longest
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages("output.pdf") as pdf:
N_plots_per_page = 10
for cols in grouper(df["walk"].unique(), N_plots_per_page):
# Initialize a grid of plots with an Axes for each walk
grid = sns.FacetGrid(df, col="walk", hue="walk", palette="tab20c",
col_wrap=2, height=1.5)
# Draw a horizontal line to show the starting point
grid.map(plt.axhline, y=0, ls=":", c=".5")
# Draw a line plot to show the trajectory of each random walk
grid.map(plt.plot, "step", "position", marker="o")
# Adjust the tick positions and labels
grid.set(xticks=np.arange(5), yticks=[-3, 3],
xlim=(-.5, 4.5), ylim=(-3.5, 3.5))
# Adjust the arrangement of the plots
grid.fig.tight_layout(w_pad=1)
pdf.savefig()
Upvotes: 2
Views: 751
Reputation: 2405
You are missing the col_order=cols
argument to the grid = sns.FacetGrid(...)
call.
Upvotes: 1