Search code examples
pythonmatplotlibseaborndata-visualizationhistogram

How to prevent gridlines showing through when using alpha


Gridlines can be set behind the plot of a filled area by using either ax.set_axisbelow(True) or plt.rc('axes', axisbelow=True) (other stack question). But when using an alpha<1 then the gridlines will also come to the front. Is there a way to still hide the gridlines or to apply selective alpha blending? I am thinking of an object-based approach where one specifies alpha between object a and b.

The answer should also be applicable to fill_between.

Example for reproducing the problem:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(2022)
x1 = np.random.normal(0, 0.8, 1000)
x2 = np.random.normal(-2, 1, 1000)
x3 = np.random.normal(3, 2, 1000)

kwargs = dict(histtype='stepfilled', alpha=.3, density=True, bins=40)
fig, ax = plt.subplots(figsize=(9, 6))

ax.hist(x1, **kwargs)
ax.hist(x2, **kwargs)
ax.hist(x3, **kwargs)

ax.set_axisbelow(True)

ax.yaxis.grid(color='gray', linestyle='dashed')
ax.xaxis.grid(color='gray', linestyle='dashed')

enter image description here


Solution

  • There is no capacity for conditional alphas in Matplotlib; that would be quite an API!

    I would just make a white version of the histograms behind the ones I wanted to be alpha:

    import numpy as np
    import matplotlib.pyplot as plt
    
    np.random.seed(2022)
    x1 = np.random.normal(0, 0.8, 1000)
    x2 = np.random.normal(-2, 1, 1000)
    x3 = np.random.normal(3, 2, 1000)
    
    
    kwargs0 = dict(histtype='stepfilled', color='w', density=True, bins=40)
    kwargs = dict(histtype='stepfilled', alpha=.3, density=True, bins=40)
    
    fig,ax = plt.subplots()
    ax.hist(x1, **kwargs0)
    ax.hist(x2, **kwargs0)
    ax.hist(x3, **kwargs0)
    ax.hist(x1, **kwargs)
    ax.hist(x2, **kwargs)
    ax.hist(x3, **kwargs)
    
    ax.set_axisbelow(True)
    
    ax.yaxis.grid(color='gray', linestyle='dashed')
    ax.xaxis.grid(color='gray', linestyle='dashed')
    

    overlapping histograms with no gridlines through them