matplotlib colorbar alternating top bottom labels

前端 未结 2 957
情歌与酒
情歌与酒 2021-01-27 09:55

First of all, this was intended as a self-answer question, because I believe it would be helpful in certain situations, e.g. in this post the author tried to hide

2条回答
  •  轮回少年
    2021-01-27 10:35

    You could add a twin Axes object and set every odd ticks there while setting every even ticks on the original Axes.

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Make the plot
    fig, ax = plt.subplots(1,1, figsize=(5,5))
    fig.subplots_adjust(bottom=0.2)
    ## Trick to have the colorbar of the same size as the plot
    box = ax.get_position() 
    cax = fig.add_axes([box.xmin, box.ymin - 0.1, box.width, 0.03])
    m = ax.matshow(np.random.random(100).reshape(10,10), aspect="auto") # Don't forget auto or the size of the heatmap will change.
    cb = plt.colorbar(m, cax=cax, orientation="horizontal")
    
    # Add twin axes 
    cax2 = cax.twiny()
    
    # get current positions and values of the ticks.
    # OR you can skip this part and set your own ticks instead.
    xt = cax.get_xticks()
    xtl = [i.get_text() for i in cax.get_xticklabels()]
    
    # set odd ticks on top (twin axe)
    cax2.set_xticks(xt[1::2])
    cax2.set_xticklabels(xtl[1::2])
    # set even ticks on  original axes (note the different object : cb != cax)
    cb.set_ticks(xt[::2])
    cb.set_ticklabels(xtl[::2])
    

    HTH

提交回复
热议问题