0

I would like to make a gif using multiple png images that I generate using matplotlib. The following function should create the required histogram plots:

def make_histogram(start, end):
    
    mean_val = statistics.mean(test_dis_item_notensor[start:end])
    max_lim = 17

    with plt.style.context('ggplot'):
        plt.hist(test_dis[start:end], bins=100, rwidth=0.9, color='indianred', range=(0, max_lim), alpha=0.8)
        plt.title('Test distributions', fontsize=22)
        plt.xlabel('Distance', fontsize=20)
        plt.ylabel('Amount', fontsize=20)
        plt.text(mean_val*1.1, max_lim*0.9, 'Mean: {:.2f}'.format(mean_val), fontsize=22)
        plt.axvline(mean_val, color='k', linestyle='dashed', linewidth=2)

        histo = plt.gcf()
        
        return histo

I tried to work with plt.gcf() but the returned object is itself not an rgb figure, what is the best way to proceed? I would like to avoid to save every image to disk and to then reload them.

Mariusmarten
  • 255
  • 3
  • 15
  • "I would like to make a gif" - Matplotlib can be used to make animations directly, without manually converting plots to PNGs: https://matplotlib.org/stable/api/animation_api.html – ForceBru May 30 '22 at 13:35
  • Also, if you already have the pngs saved, you can join them into a video using ffmpeg: https://stackoverflow.com/questions/24961127/how-to-create-a-video-from-images-with-ffmpeg – K.Cl May 30 '22 at 13:39
  • Thanks for the answers. The pngs are not saved yet (and I would like to avoid that). The animation api is an option but isn't there an easy way to work with the figure objects? – Mariusmarten May 30 '22 at 13:44
  • It looks like the animation API expects one figure that you update each frame, not a sequence of figure objects. You could quite easily modify your code to modify an existing figure instead of creating a new one if you change from the implicit to the explicit method. E.g. `fig, ax = plt.subplots()` outside the function, then `ax.hist(...)` inside the function you provide to FuncAnimation. Don't forget to clear the axes before adding a new one, otherwise I think you'll accumulate histograms. – K.Cl May 30 '22 at 14:00

0 Answers0