Search code examples
pythonmatplotlibcolorbar

Multiple scatter plots with two colorbars


I am trying to make a plot that has three scatterplots in it, each showing two kinds of data. I would like to show to colorbars corresponding to this data (i.e., separately for the shades of orange and purples). I know how to make a single plot with multiple colorbars and I know how to make multiple plots with a common colorbar but I can't figure out how to put multiple colorbars on a plot with multiple subplots.

Here is an example for making multiple plots:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=3)
images =[]
for i in range(3):
    images.append([axes[i].scatter(np.random.random(10), np.random.random(10), c = np.random.random(10), vmin=0, vmax=1, cmap="Purples_r"),

axes[i].scatter(np.random.random(10),np.random.random(10), c = 
np.random.random(10), vmin=0, vmax=1, cmap="Oranges_r")])

plt.show()

UPDATE: Adding the following code returns two colorbars:

fig.colorbar(images[0][1], ax=axes, fraction=.05)
fig.colorbar(images[0][2], ax=axes, fraction=.05)

I am assuming that keeping fixed common vmin and vmax values for all scatterplots assures that the scale is consistent between plots.


Solution

  • Ok, so it seems like adding the following to the code:

    fig.colorbar(images[0][0], ax=axes, fraction=.05)
    fig.colorbar(images[0][1], ax=axes, fraction=.05)
    

    I tried this yesterday and it wasn't working, I must have had something in my notebook memory.

    And just for completeness, here is the complete code:

    import numpy as np
    import matplotlib.pyplot as plt
    
    fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 3))
    
    images =[]
    for i in range(3):
        images.append([axes[i].scatter(np.random.random(10), np.random.random(10), 
        c = np.random.random(10), vmin=0, vmax=1, cmap="Purples_r"),
    
        axes[i].scatter(np.random.random(10),np.random.random(10), 
        c = np.random.random(10), vmin=0, vmax=1, cmap="Oranges_r")])
    
    fig.colorbar(images[0][0], ax=axes, fraction=.05)
    fig.colorbar(images[0][1], ax=axes, fraction=.05)
    
    plt.show()
    

    and here is a visual of what I was looking for:

    enter image description here