At the moment I'm learning how to work with matplotlib
and seaborn
and the concept behind it seems quite strange to me. One would expect the sns.countplot
function to return an object that has a .plot()
and .save()
fuction so one could work with the plot in a different function.
Instead it seems that every call to sns.countplot
overwrites the previous object (see MWE).
So one the one hand It would be grate if someone could provide a explanation of the matplotlib
and seaborn
interface (or have some good doku linked). Since all the doku I read wasn't of any great help.
On the other hand I have a function that returns some plots, which I want to save as an .pdf
file with one plot per page. I found this similar question but can't copy the code over in a way to make my MWE work.
from matplotlib.backends.backend_pdf import PdfPages
import seaborn as sns
def generate_plots():
penguins = sns.load_dataset("penguins")
countplot_sex = sns.countplot(y='sex', data=penguins)
countplot_species = sns.countplot(y='species', data=penguins)
countplot_island = sns.countplot(y='island', data=penguins)
# As showes
# print(countplot_sex) -> AxesSubplot(0.125,0.11;0.775x0.77)
# print(countplot_species) -> AxesSubplot(0.125,0.11;0.775x0.77)
# print(countplot_island) -> AxesSubplot(0.125,0.11;0.775x0.77)
# All three variables contain the same object
return(countplot_sex, countplot_species, countplot_island)
def plots2pdf(plots, fname): # from: https://stackoverflow.com/a/21489936
pp = PdfPages('multipage.pdf')
for plot in plots:
pass
# TODO save plot
# Does not work: plot.savefig(pp, format='pdf')
pp.savefig()
pp.close()
def main():
plots2pdf(generate_plots(), 'multipage.pdf')
if __name__ == '__main__':
main()
My Idea is to have a somewhat decent software architecture with one function generating plots and another function saving them.