Home > Net >  How to prevent gridlines showing through when using alpha
How to prevent gridlines showing through when using alpha

Time:07-02

Gridlines can be set behind the plot of a filled area by using either ax.set_axisbelow(True) or plt.rc('axes', axisbelow=True) (enter image description here

CodePudding user response:

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

CodePudding user response:

  • This question is relevant to those using seaborn, since it's is a high-level api for matplotlib.
  • A seaborn solution similarly requires a white background, like that produced by enter image description here

    Without hue=

    fig, ax = plt.subplots(figsize=(9, 6))
    
    sns.histplot(data=df, x='values', stat='density', bins=40, color='white', element='step', ax=ax, alpha=1)
    sns.histplot(data=df, x='values', stat='density', bins=40, alpha=0.3, element='step', ax=ax)
    ax.set_axisbelow(True)
    ax.grid()
    

    enter image description here


    • This is the plot without alpha=1 for the 'white' plot.

    enter image description here

  • Related