Search code examples
pythonpython-2.7matplotlibsubplotcolorbar

2 subplots sharing y-axis (no space between) with single color bar


Does anyone have a matplotlib example of two plots sharing the y-axis (with no space between the plots) with a single color bar pertaining to both subplots? I have not been able to find examples of this yet.


Solution

  • I created the following code based on your question. Personally I do not like it to have no space between the subplots at all. If you do want to change this at some point all you need to do is to replace plt.subplots_adjust(wspace = -.059) with plt.tight_layout().

    Hope this helps

    import numpy
    import matplotlib.pyplot as plt
    from mpl_toolkits.axes_grid1 import make_axes_locatable
    
    #Random data
    data = numpy.random.random((10, 10))
    
    fig = plt.figure()
    
    ax1 = fig.add_subplot(1,2,1, aspect = "equal")
    ax2 = fig.add_subplot(1,2,2, aspect = "equal", sharey = ax1)  #Share y-axes with subplot 1
    
    #Set y-ticks of subplot 2 invisible
    plt.setp(ax2.get_yticklabels(), visible=False)
    
    #Plot data
    im1 = ax1.pcolormesh(data)
    im2 = ax2.pcolormesh(data)
    
    #Define locations of colorbars for both subplot 1 and 2
    divider1 = make_axes_locatable(ax1)
    cax1 = divider1.append_axes("right", size="5%", pad=0.05)
    
    divider2 = make_axes_locatable(ax2)
    cax2 = divider2.append_axes("right", size="5%", pad=0.05)
    
    #Create and remove the colorbar for the first subplot
    cbar1 = fig.colorbar(im1, cax = cax1)
    fig.delaxes(fig.axes[2])
    
    #Create second colorbar
    cbar2 = fig.colorbar(im2, cax = cax2)
    
    #Adjust the widths between the subplots
    plt.subplots_adjust(wspace = -.059)
    
    plt.show()
    

    The result is the following:

    enter image description here