Search code examples
pythonmatplotlibfiguremeasure

Measure width of grid in yaxis units in matplotlib


Is there some way to measure the width of the grid lines in terms of the units used in the y axis?

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

t = np.arange(0.0, 2.0, 0.01)
s = 1 + np.sin(2 * np.pi * t)

fig, ax = plt.subplots(constrained_layout=True)

ax.yaxis.set_tick_params(which='minor', width=5)
ax.plot(t, s)
ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
ax.grid(linewidth=5, axis='y', which='both')
ax.set_ylim(0, 2.25)

plt.show()

Screenshot


Solution

  • Thanks to Trenton McKinney, here is my stab at the problem. I had to change the line where I set the linewidth so that it used a variable lw as I haven't been able to figure out how to get the linewidth from the ax object.

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib as mpl
    
    t = np.arange(0.0, 2.0, 0.01)
    s = 1 + np.sin(2 * np.pi * t)
    
    fig, ax = plt.subplots(constrained_layout=True)
    
    ax.yaxis.set_tick_params(which='minor', width=5)
    ax.plot(t, s)
    ax.yaxis.set_major_locator(mpl.ticker.MultipleLocator(0.50))
    ax.yaxis.set_minor_locator(mpl.ticker.MultipleLocator(0.25))
    # ax.grid(linewidth=5, axis='y', which='both')
    lw = 5
    ax.grid(linewidth=lw, axis='y', which='both')
    ax.set_ylim(0, 2.25)
    
    def get_DaUPP(fig, ax):
        # Points per inch
        PPI = 72
    
        # Display units per inch
        figsizeDispUnits = np.diff(fig.transFigure.transform([(0, 0), (1, 1)]), 1, 0)
    
        DiUPI = np.divide(figsizeDispUnits, fig.get_size_inches())
    
        # Display units per data unit
        axDispUnits = np.diff(ax.transData.transform([(ax.get_xlim()[0], ax.get_ylim()[0]), (ax.get_xlim()[1], ax.get_xlim()[1])]), 1, 0)
        axDataUnits = np.diff([(ax.get_xlim()[0], ax.get_ylim()[0]), (ax.get_xlim()[1], ax.get_xlim()[1])], 1, 0)
        DiUPDaU = np.divide(axDispUnits, axDataUnits)
    
        # Data units per inch
        DaUPI = np.divide(DiUPI, DiUPDaU)
    
        # Data unit per point
        DaUPP = DaUPI / PPI
    
        return DaUPP.flatten()
    
    # Width of grid in yaxis units
    lw * get_DaUPP(fig, ax)[1]