Use a loop to plot n charts Python

前端 未结 4 429
盖世英雄少女心
盖世英雄少女心 2020-12-02 09:25

I have a set of data that I load into python using a pandas dataframe. What I would like to do is create a loop that will print a plot for all the elements in their own fram

4条回答
  •  一个人的身影
    2020-12-02 10:06

    Use a dictionary!!

    You can also use dictionaries that allows you to have more control over the plots:

    import matplotlib.pyplot as plt
    #   plot 0     plot 1    plot 2   plot 3
    x=[[1,2,3,4],[1,4,3,4],[1,2,3,4],[9,8,7,4]]
    y=[[3,2,3,4],[3,6,3,4],[6,7,8,9],[3,2,2,4]]
    
    plots = zip(x,y)
    def loop_plot(plots):
        figs={}
        axs={}
        for idx,plot in enumerate(plots):
            figs[idx]=plt.figure()
            axs[idx]=figs[idx].add_subplot(111)
            axs[idx].plot(plot[0],plot[1])
    return figs, axs
    
    figs, axs = loop_plot(plots)
    

    Now you can select the plot that you want to modify easily:

    axs[0].set_title("Now I can control it!")
    

    Of course, is up to you to decide what to do with the plots. You can either save them to disk figs[idx].savefig("plot_%s.png" %idx) or show them plt.show(). Use the argument block=False only if you want to pop up all the plots together (this could be quite messy if you have a lot of plots). You can do this inside the loop_plot function or in a separate loop using the dictionaries that the function provided.

提交回复
热议问题