Search code examples
pythonmatplotlibcolorslabel

Matplotlib Tick lines and labels of different color


I am trying to plot a 2d image using a specific colormap in matplotlib and I need to change the color of the ticks to white. But when I do so, the labels or tick numbers change of color too and they become invisible on a white background.

How can I change only the color of the tick lines and not the color of their label or associated number???

Example

    import matplotlib.pyplot as plt
    import numpy as np


    fig=plt.figure()
    ax=fig.add_subplot(111) 
    pc=ax.pcolormesh(xf,yf,F, vmin=F.min(), vmax=F.max(),  cmap=colormap)
    fig.colorbar(pc,orientation='horizontal',label=r'Intensity',format='%1.1f', ticks=np.arange(-0.1,0.6,0.1), pad=0.1)
    ax.set_xlabel("RA offset [arcsec]")
    ax.set_ylabel("DEC offset [arcsec]")
    ax.set_xlim(3.0,-3.0)
    ax.set_ylim(-3.0,3.0)

    ########## ticks

    ### x axis

    major_ticks = np.arange(-2.0, 3.0, 2.0)                                              
    minor_ticks = np.arange(-3.0, 4.0, 1.0)                                               


    ax.set_xticks(major_ticks)                                                       
    ax.set_xticks(minor_ticks, minor=True)                                           
    ax.set_yticks(major_ticks)                                                       
    ax.set_yticks(minor_ticks, minor=True) 

Solution

  • after making your Axes and setting the appropriate tick locations, you can access the ticks with ax.get_xticklines() and ax.get_yticklines(). If you iterate over all the xticks or yticks, you can change their colours using set_color()

    For minor ticks, you can use ax.xaxis.get_minorticklines(). Note that you could also use ax.xaxis.get_majorticklines() in place of ax.get_xticklines() if you prefer.

    for tick in ax.get_xticklines():
        tick.set_color('red')
    
    for minortick in ax.xaxis.get_minorticklines():
        minortick.set_color('r')
    
    for tick in ax.get_yticklines():
        tick.set_color('green')