Histograms are getting overlapped on each other

I’m trying to plot figures and save it as a file and show it in HTML. I’m using flask and putting all the code for histogram generation in a function. But each time the histogram is plotted based on different input of the users, each histogram are getting overlapped on each other.

I’m expecting it to overwrite the image already saved as the figure and create a new figure with the histogram in it. Here’s my code…

            plt.hist(course_student_marks)
            plt.xlabel('Marks')
            plt.ylabel('Frequency')
            plt.savefig('static/assets/histogram_image.png')

I don’t see you creating a new figure or closing the old one, so that’s expected behaviour. Note that plt.savefig just saves the figure, it doesn’t close it. You need to close it with plt.close explicitly.

Note that this is specific to using the pyplot interface, which is geared towards interactive figures. Since this is somewhere in Flask, you likely don’t need a GUI, and probably should use the explicit interface by creating a Figure from matplotlib.figure.Figure.

1 Like