Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Seaborn palettes - prevent recycling of colors

Seaborn allows defining color palettes that contain multiple colors, useful for charts with many lines. However, when setting the palette to one with multiple colors, only the first six are used, after which colors recycle, making it hard to distinguish lines. This can be overridden by explicitly calling the palette, but that's not convenient. Is there a way to force the Seaborn current palette not to recycle colors, when more than 6 are defined?

Example:

from matplotlib import pyplot as plt
import pandas as pd
import seaborn as sb

# Define a palette with 8 colors
cmap = sb.blend_palette(["firebrick", "palegreen"], 8) 
sb.palplot(cmap)

palette with 6 colors

# Set the current palette to this; only 6 colors are used
sb.set_palette(cmap)
sb.palplot(sb.color_palette() )

palette with 6 colors

df = pd.DataFrame({x:[x*10, x*10+5, x*10+10] for x in range(8)})
fig, (ax1, ax2) = plt.subplots(2,1,figsize=(4,6))
# Using the current palette, colors repeat 
df.plot(ax=ax1) 
ax1.legend(bbox_to_anchor=(1.2, 1)) 
# using the palette that defined the current palette, colors don't repeat
df.plot(ax=ax2, color=cmap) 
ax2.legend(bbox_to_anchor=(1.2, 1))  ;

charts with 6 or 8 colors used

like image 752
iayork Avatar asked Oct 10 '14 14:10

iayork


People also ask

What can we do in the color palettes in Seaborn?

You can build color palettes using the function sns. color_palette() . This function can take any of the Seaborn built-in palettes (see below). You can also build your own palettes by passing in a list of colors in any valid Matplotlib format, including RGB tuples, hex color codes, or HTML color names.

What is CMAP in Seaborn?

cmapmatplotlib colormap name or object, or list of colors, optional. The mapping from data values to color space.

How do I change my color palette in Seaborn heatmap?

You can change the color of the seaborn heatmap by using the color map using the cmap attribute of the heatmap.


1 Answers

Solution (thanks to @tcaswell for the pointer): Set the palette explicitly using all colors:

# Setting the palette using defaults only finds 6 colors
sb.set_palette(cmap)
sb.palplot(sb.color_palette() )
sb.palplot(sb.color_palette(n_colors=8) )

# but setting the number of colors explicitly allows it to use them all
sb.set_palette(cmap, n_colors=8)
# Even though unless you explicitly request all the colors it only shows 6
sb.palplot(sb.color_palette() )
sb.palplot(sb.color_palette(n_colors=8) )

enter image description hereenter image description hereenter image description hereenter image description here

# In a chart, the palette now has access to all 8 
fig, ax1 = plt.subplots(1,1,figsize=(4,3)) 
df.plot(ax=ax1) 
ax1.legend(bbox_to_anchor=(1.2, 1)) ;

enter image description here

like image 129
iayork Avatar answered Sep 27 '22 21:09

iayork