【发布时间】:2020-10-09 09:47:45
【问题描述】:
目前我正在学习如何使用matplotlib 和seaborn,它背后的概念对我来说似乎很奇怪。人们会期望sns.countplot 函数返回一个具有.plot() 和.save() 函数的对象,因此可以在不同的函数中使用绘图。
相反,似乎每次调用 sns.countplot 都会覆盖之前的对象(请参阅 MWE)。
所以一方面如果有人可以提供matplotlib 和seaborn 接口的解释(或有一些好的doku 链接),那将是非常高兴的。由于我阅读的所有独库都没有太大帮助。
另一方面,我有一个返回一些图的函数,我想将其保存为.pdf 文件,每页一个图。我发现了类似的question,但无法复制代码以使我的 MWE 工作。
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()
我的想法是有一个有点像样的软件架构,一个函数生成图,另一个函数保存它们。
【问题讨论】:
标签: python matplotlib pdf save seaborn