Search code examples
pythonmatplotlibscatter

How to plot scatter with different edgecolor defined by an array ranged -0.1 to 0.1


def scatterplot(part):
    colors = part['deltf']
    c = plt.cm.coolwarm(colors)
    plt.scatter(part['fnormal'], part['mu']/part['E'], c='w',edgecolors=c,alpha=0.5, 
                   cmap='coolwarm', marker="o")

The edge color only has one color on the output figure by running this code. I found plt.cm.coolwarm need positive value, but I need negative value presented.

I would appreciate it if anyone could help me.


Solution

  • You need to normalize values to [0, 1] to map the color. pls see code below:

    import matplotlib as mpl
    
    xx = np.linspace(-0.1, 0.1, 100)
    
    def normalize(xx):
        vmin = xx.min()
        vmax = xx.max()
        return (xx - vmin)/(vmax-vmin)
    
    cmap = mpl.cm.coolwarm
    norm = mpl.colors.Normalize(vmin=-0.1, vmax=0.1)
        
    def scatterplot(xx):
        colors = normalize(xx)
        c = plt.cm.coolwarm(colors)
        fig, ax = plt.subplots(1, 1, figsize=(7.2, 7.2))
        ax.scatter(xx, np.sin(xx), c='w',edgecolors=c,alpha=0.5, cmap='coolwarm', marker="o")
        cbar = plt.colorbar(plt.cm.ScalarMappable(norm=norm, cmap=cmap), ax=ax)
    scatterplot(xx)
    

    Summary:

    • to map color, use normalized values
    • to plot data, use original values

    enter image description here