pythonmatplotlibseabornscatter-plotkdeplot

How to change colors of a variable in a kdeplot or scatterplot


From this dataframe that represent the position of a fish according to different months:

X      Y      Month
2040   2760    1
2041   2580    1 
2045   2762    1 
2047   2763    2
2053   2774    3

and through this seaborn script:

fig,ax=plt.subplots()
kde = sns.kdeplot(data=HR25, x='X', y='Y', shade=True, ax=ax, levels=levels_, cmap="Reds", 
alpha=0.9)
ax.set_xlim([x_min-10, x_max+10])
ax.set_ylim([y_min-10, y_max+10])
ax.scatter(X, Y, c=months, edgecolors='black', picker=True, s=17)
ax.set_aspect('equal')
plt.show()

i have been able to create this figure which represent the positions of a fish over one year according to months (the red area in the background is the home range of the animal calculated with kernel seaborn method): enter image description here

Actually, I would like to change the colours of the points related to the months, so I create a distinct palette specifing colours for each month:

palette = {1:"tab:blue", 2:"tab:orange", 3:"tab:purple", 4:"tab:green", 5:"tab:red", 6:"tab:pink", 7:"tab:brown", 8:"tab:yellow", 9:"tab:olive", 10:"tab:black", 11:"tab:cyan", 12:"tab:gray"}

However, when i add the palette to ax.scatter like this:

fig,ax=plt.subplots()
    kde = sns.kdeplot(data=HR25, x='X', y='Y', shade=True, ax=ax, levels=levels_, cmap="Reds", 
    alpha=0.9)
    ax.set_xlim([x_min-10, x_max+10])
    ax.set_ylim([y_min-10, y_max+10])
    ax.scatter(X, Y, c=months, edgecolors='black', picker=True, s=17, palette=palette)
    ax.set_aspect('equal')
    plt.show()

all points disappear!


Solution

  • In your case, when you call ax.scatter you're not actually using the Seaborn scatterplot function. Instead, you're using the Matplotlib scatter function, which does not have a palette or picker keyword argument. Rather than:

    ax.scatter(X, Y, c=months, edgecolors='black', picker=True, s=17, palette=palette)
    

    try:

    sns.scatterplot(X, Y, c=months, edgecolors='black', picker=True, s=17, palette=palette, ax=ax)
    

    Note: tab:yellow and tab:black are not in Matplotlib's tableau palette, so you should remove the tab: in the strings for those values.

    If you did want to use Matplotlib's scatter, you could set the colours by setting 'axes.prop_cycle' in the rcParams, e.g.,:

    import matplotlib as mpl
    from cycler import cycler
    
    mpl.rcParams['axes.prop_cycle'] = cycler(
        color=list(palette.values())
    )