pythonmatplotlibplothistogramalpha

Plotting transparent histogram with non transparent edge


I am plotting a histogram, and I have three datasets which I want to plot together, each one with different colours and linetype (dashed, dotted, etc). I am also giving some transparency, in order to see the overlapping bars.

The point is that I would like the edge of each bar not to become transparent as the inner part does. Here is an example:

import matplotlib.pyplot as plt
import numpy as np

x = np.random.random(20)
y =np.random.random(20)
z= np.random.random(20)

fig = plt.figure()
ax = fig.add_subplot(111)
ax.hist(x, bins=np.arange(0, 1, 0.1), ls='dashed', alpha = 0.5, lw=3, color= 'b')
ax.hist(y, bins=np.arange(0, 1, 0.1), ls='dotted', alpha = 0.5, lw=3, color= 'r')
ax.hist(z, bins=np.arange(0, 1, 0.1), alpha = 0.5, lw=3, color= 'k')
ax.set_xlim(-0.5, 1.5)
ax.set_ylim(0, 7)
plt.show()

enter image description here


Solution

  • plt.hist accepts additional keyword arguments that are passed to the constructor for matplotlib.patches.Patch. In particular you can pass an fc= argument which lets you set the patch facecolor using an (R, G, B, A) tuple when you create the histograms. Changing the alpha value of the facecolor does not affect the transparency of the edges:

    ax.hist(x, bins=np.arange(0, 1, 0.1), ls='dashed', lw=3, fc=(0, 0, 1, 0.5))
    ax.hist(y, bins=np.arange(0, 1, 0.1), ls='dotted', lw=3, fc=(1, 0, 0, 0.5))
    ax.hist(z, bins=np.arange(0, 1, 0.1), lw=3, fc=(0, 0, 0, 0.5))
    

    enter image description here