Luis Miguel Luis Miguel - 1 year ago 79
Python Question

Setting the alpha value of a custom palette in seaborn

I am modifying a piece of code I found in the seaborn documentation, in order to design a palette that is common to matplotlib and seaborn. The code below work great, however, if you plot many points (5000 in my example), the darker color dominates the chart.
A quick fix to that is to set the alpha value of one (or both) colors, to something low.

custom = ["#D1EC9C", "#F1EBF4"]
# construct cmap
my_cmap = ListedColormap(custom)

N = 5000
data1 = np.random.randn(N)
data2 = np.random.randn(N)
colors = np.linspace(0,1,N)
plt.scatter(data1, data2, c=colors, cmap=my_cmap)

Does anybody know how to set the alpha value of a custom Seaborn palette?
enter image description here

Answer Source

You can set the alpha as part of the colors in your colormap:

custom = [(0xD1/0xFF, 0xEC/0xFF, 0x9C/0xFF, 1), (0xF1/0xFF, 0xEB/0xFF, 0xF4/0xFF, 0.5)]
my_cmap = mpl.colors.ListedColormap(custom)

Here I gave the second color alpha of 0.5; you can do it with the other color if you want.

Note that seaborn is not really involved here. The colors of the plot are determined by the colors you passed in the colormap; seaborn's palette has no impact. The only effect seaborn has on your plot is in the formatting of the background, axes, grid, etc.

As I said in a comment, though, I believe that using alpha for only one color will not make your plot look good. If one color is still opaque, it will still cover up dots of the other color, only more so (because now the other color will be fainter). Also, if you are going to use alpha (and maybe even if you aren't), the grayish color you chose is probably not a good idea, because it is similar to the gray background seaborn provides, making it difficult to distinguish the gray dots from the gray background.