Save plot to image file instead of displaying it using Matplotlib

前端 未结 20 1432
一生所求
一生所求 2020-11-22 06:07

I am writing a quick-and-dirty script to generate plots on the fly. I am using the code below (from Matplotlib documentation) as a starting point:

from pylab         


        
20条回答
  •  误落风尘
    2020-11-22 06:30

    The other answers are correct. However, I sometimes find that I want to open the figure object later. For example, I might want to change the label sizes, add a grid, or do other processing. In a perfect world, I would simply rerun the code generating the plot, and adapt the settings. Alas, the world is not perfect. Therefore, in addition to saving to PDF or PNG, I add:

    with open('some_file.pkl', "wb") as fp:
        pickle.dump(fig, fp, protocol=4)
    

    Like this, I can later load the figure object and manipulate the settings as I please.

    I also write out the stack with the source-code and locals() dictionary for each function/method in the stack, so that I can later tell exactly what generated the figure.

    NB: Be careful, as sometimes this method generates huge files.

提交回复
热议问题