How can i overlap two parts in plt.hist?

Viewed 96

The image is here

my code:

plt.hist(all_loss[0][-1][clean_idx].numpy(), bins=20,density=True,alpha=0.5,stacked=True,facecolor="cornflowerblue",label='clean')
plt.hist(all_loss[0][-1][noisy_idx].numpy(), bins=20, density=True,alpha=0.5,stacked=True,facecolor="pink",label='noisy')

The picture I get: The picture is here

1 Answers

You need to include both datasets in the same call to plt.hist. Note that you likely also do not want to set stacked=True. Instead, I have set histtype='stepfilled', and use a transparency setting, alpha=0.5, to show the overlap. If for some reason, you don't want identical bins for the two datasets, you can use bins=[10, 20], for example (as I've done for the colour settings and the labels).

There are actually multiple examples the Matplotlib examples of histograms (although none shows a filled overlap with transparancy; that is sadly missing).

from matplotlib import pyplot as plt
import numpy as np

rng = np.random.default_rng()
a = rng.normal(15, 5, 200)
b = rng.normal(20, 5, 200)

plt.hist([a, b], 20, color=['cornflowerblue', 'pink'], histtype='stepfilled', density=True, alpha=0.5, label=['clean', 'noisy'])
plt.legend()
plt.show()

enter image description here


I would also suggest to have a look at the Seaborn hist function. Seaborn extends the Matplotlib functionality, and often has this kind of graphs built-in.

Related