Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save a sns.facetgrid to a pdf

I have a dataframe that looks like this:

import pandas as pd
foo = pd.DataFrame({'occasions': ['a', 'a', 'b', 'b'], 'val':[1,1,1,2]})

I am trying to create a histogram with a facet using seaborn like this and I want to save that image to a pdf, so i am doing this:

import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

pdf = PdfPages('exploration.pdf')
g = sns.FacetGrid(foo, col="occasions", margin_titles=True)
g.map(plt.hist,'val', color="steelblue")
g.set_titles(col_template = '{col_name}')
g.fig.suptitle('title')
plot_fig(g, pdf)

where

def plot_fig(plot, pdf):
    try:
        fig = plot.draw()
    except:
        fig = plot
    pdf.savefig(fig, height=10, width=18, dpi=500, bbox_inches='tight', pad_inches=0.5)
    plt.close()

But I get an error: ValueError: No figure <seaborn.axisgrid.FacetGrid object at 0x7f1ca2300780>, any ideas why and how I could fix that ?

like image 390
quant Avatar asked Dec 19 '25 04:12

quant


1 Answers

I don't know what your PdfPages('exploration.pdf') file looks like, thus I'cant make sure that this works, but in general saving figures should work like this:

def plot_fig(plot, pdf):
    try:
        fig = plot.draw()
    except:
        fig = plot
    pdf.savefig(fig.fig, height=10, width=18, dpi=500, bbox_inches='tight', pad_inches=0.5)
    plt.close()

What is called fig in your function is the seaborn.axisgrid.FacetGrid. To access the underlying matplotlib.figure and use its savefig method, you need to select it using fig.fig. Maybe renaming the facet grid to something else than fig might help reducing the confusion.

like image 69
JE_Muc Avatar answered Dec 21 '25 19:12

JE_Muc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!