0

I am plotting multiple histograms in Matplotlib in one figure. This is working well when displaying it by using show(). When saving the figure using savefig(), only one or sometimes no graph is shown. Also, the quality of the figure is not as good as the one produced by show().

This is my code:

def plot_delta_ts_in_histo2(key1, values1, key2, values2):
    fig = plt.figure()
    plt.hist(values1, bins=[x for x in np.arange(0, 600, 1)], density=True, alpha=0.25, label=key1)
    plt.hist(values2, bins=[x for x in np.arange(0, 600, 1)], density=True, alpha=0.25, label=key2)
    plt.xlabel('Time in seconds')
    plt.ylabel('Number of elements')
    plt.legend(loc='upper right')
    fig.savefig("./Plots/" + key1 + "_" + key2 + '.png', dpi=fig.dpi)
    plt.show()
    fig.clf()

The "key"-parameters are strings, while the "values"-parameters are a list of floats.

Examples: Figure produced by shown()

Figure produced by savefig()

How can I fix this problem and how can i improve the quality of the plots?

Thanks in advance!

AndiYo
  • 43
  • 6
  • It could help to increase the dpi, e.g. 600 dpi for the png. See also https://stackoverflow.com/questions/13714454/specifying-and-saving-a-figure-with-exact-size-in-pixels – JohanC Jun 19 '21 at 09:49

1 Answers1

0

I think your problem is the opacity of the plots, you set alpha=0.25, and maybe you should set it to some more significant number. On the other hand, the fig.dpi and I think it is 100 in default(for figsize=(12,6)).

Morteza
  • 26
  • 6
  • Hmm, I tried altering the alpha variable to a higher value and sadly it didn't change anything... – AndiYo Jun 18 '21 at 20:20