Search code examples
pythonmatplotlibcolors

Is it possible to assign a colourmap for edgecolors in matplotlib?


Assuming one needs to change the edge colour of a matplotlib marker depending on some variable, is it possible to assign a some sort of discrete colour-map for the edge colour of the marker? This is similar to changing the face-colour of the marker by cmap.

When showing limits using arrows outside a plot's range, I cannot seem to vary the arrow colour depending on another variable. eg: in the code below the colour of the arrow doesn't change as a function of z.

plt.scatter(x,y, c=z, marker=u'$\u2191$', s=40,cmap=discrete_cmap(4, 'cubehelix') )

Solution

  • You can do this using the edgecolors argument to scatter.

    You need to make a list of colours to feed to scatter. We can do this using your chosen colormap and a Normalize instance, to rescale to z function to the 0-1 range.

    I'm assuming your discrete_cmap function is something like the one linked here.

    import matplotlib.pyplot as plt
    import matplotlib.colors as colors
    import numpy as np
    
    # def discrete_cmap() is omitted here...
    
    # some sample data
    x = np.linspace(0,10,11)
    y = np.linspace(0,10,11)
    z = x+y
    
    # setup a Normalization instance
    norm = colors.Normalize(z.min(),z.max())
    
    # define the colormap
    cmap = discrete_cmap(4, 'cubehelix')
    
    # Use the norm and cmap to define the edge colours
    edgecols = cmap(norm(z))
    
    # Use that with the `edgecolors` argument. Set c='None' to turn off the facecolor
    plt.scatter(x,y, edgecolors=edgecols, c = 'None', marker='o', s=40 )
    
    plt.show()
    

    enter image description here