1

Using pdf pages below results in a pdf without the plots.
Is it possible to resolve this for plots from pivot tables?

import seaborn as sns
titanic = sns.load_dataset('titanic')

import matplotlib.backends.backend_pdf
pdf = matplotlib.backends.backend_pdf.PdfPages("seaborn.pdf")

# Loop over list 's' for plots
with PdfPages(r'seaborn.pdf') as export_pdf:
    s = ['embark_town', 'class', 'embarked']
    for i in s:
        fig = plt.figure(figsize = [10, 5]);
        ax = titanic.pivot_table(values='fare', columns = i, index='sex', aggfunc='sum').plot()
        export_pdf.savefig(fig, bbox_inches='tight')

IOIOIOIOIOIOI
  • 277
  • 3
  • 15

1 Answers1

0

Use subplots to get both fig and ax then set the ax argument of DataFrame.plot:

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

titanic = sns.load_dataset('titanic')

pdf = PdfPages("seaborn.pdf")

# Loop over list 's' for plots
with PdfPages(r'seaborn.pdf') as export_pdf:
    s = ['embark_town', 'class', 'embarked']
    for i in s:
        fig, ax = plt.subplots(figsize=[10, 5])
        titanic.pivot_table(
            'fare', columns=i, index='sex', aggfunc='sum'
        ).plot(ax=ax)
        export_pdf.savefig(fig, bbox_inches='tight')

Page 1:

page 1

Page 2:

page 2

Page 3:

page 3

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
  • Many thanks, typically the addition of bbox_to_anchor = (1,1) for plots places the legend outside the plot. Do you know why this is not the case here? fig, ax = plt.subplots(figsize=[10, 5]) titanic.pivot_table( 'fare', columns=i, index='age', aggfunc='sum' ).plot(ax=ax).legend(bbox_to_anchor=(1, 1)) – IOIOIOIOIOIOI Jul 26 '21 at 19:03
  • You're going to have to set `legend=False` in `plot` if you want to move the legend. `titanic.pivot_table('fare', columns=i, index='sex', aggfunc='sum').plot(ax=ax, legend=False).legend(bbox_to_anchor=(1, 1))` – Henry Ecker Jul 26 '21 at 19:26