Color scheme and color palettes

There are three general kinds of color palettes available in seaborn--qualitative, diverging, and sequential:

  • Qualitative palettes are best for data with discrete levels or nominal or categorical data. Custom qualitative palettes can be created by providing a list of Matplotlib colors to seaborn.color_palette.
  • Diverging palettes are used for highlighting low and high values in a figure, with a neutrally colored midpoint. Custom diverging palettes can be created by passing two hue values plus the optional lightness and saturation values for the extremes to the seaborn.diverging_palette function.
  • Sequential palettes are usually used for quantitative data that progresses continuously from low to high.
    Custom sequential palettes can be created by providing a single Matplotlib color to seaborn.light_palette or seaborn.dark_palette, which produces a palette that changes gradually from light or dark desaturated values to the seed color.

In the next example, we are going to plot the most commonly used qualitative, diverging, and sequential palettes, as well as a few custom palettes:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap


def palplot(pal, ax):
"""Plot the values in a color palette as a horizontal array.
Adapted from seaborn.palplot

Args:
p : seaborn color palette
ax : axes to plot the color palette
"""
n = len(pal)
ax.imshow(np.arange(n).reshape(1, n),
cmap=ListedColormap(list(pal)),
interpolation="nearest", aspect="auto")
ax.set_xticks(np.arange(n) - .5)
ax.set_yticks([-.5, .5])
ax.set_xticklabels([])
ax.set_yticklabels([])


palettes = {"qualitative": ["deep", "pastel", "bright", "dark",
"colorblind", "Accent", "Paired",
"Set1", "Set2", "Set3", "Pastel1",
"Pastel2", "Dark2"],
"diverging": ["BrBG", "PiYG", "PRGn", "PuOr", "RdBu",
"RdBu_r", "RdGy", "RdGy_r", "RdYlGn",
"coolwarm"],
"sequential": ["husl", "Greys", "Blues", "BuGn_r",
"GnBu_d", "plasma", "viridis","cubehelix"]}

#Reset to default Seaborn style
sns.set()

# Create one subplot per palette, the x-axis is shared
fig, axarr = plt.subplots(13, 3, sharex=True, figsize=(12,11))

# Plot 9 color blocks for each palette
for i, palette_type in enumerate(palettes.keys()):
for j, palette in enumerate(palettes[palette_type]):
pal = sns.color_palette(palettes[palette_type][j], 9)
palplot(pal, axarr[j,i])
axarr[j,i].set_xlabel(palettes[palette_type][j])

# Plot a few more custom diverging palette
custom_diverging_palette = [
sns.diverging_palette(220, 20, n=9),
sns.diverging_palette(10, 220, sep=80, n=9),
sns.diverging_palette(145, 280, s=85, l=25, n=9)
]

for i, palette in enumerate(custom_diverging_palette):
palplot(palette, axarr[len(palettes["diverging"])+i,1])
axarr[len(palettes["diverging"])+i,1].set_xlabel("custom diverging
{}".format(i+1))

# Plot a few more custom sequential palette
other_custom_palette = [
sns.light_palette("green", 9),
sns.light_palette("green", 9, reverse=True),
sns.dark_palette("navy", 9),
sns.dark_palette("navy", 9, reverse=True),
sns.color_palette(["#49a17a","#4aae82","#4eb98a","#55c091","#c99b5f",
"#cbb761","#c5cc62","#accd64","#94ce65"])
]

for i, palette in enumerate(other_custom_palette):
palplot(palette, axarr[len(palettes["sequential"])+i,2])
axarr[len(palettes["sequential"])+i,2].set_xlabel("custom sequential
{}".format(i+1))

# Reduce unnecessary margin space
plt.tight_layout()

# Show the plot
plt.show()

The expected output is as follows:

To change the color scheme of a Seaborn plot, we can use either the color or palette parameter available in most Seaborn functions. The color parameter supports a single color that will be applied to all of the elements. On the other hand, palette supports a range of colors to differentiate levels of the hue variable.

Some Seaborn functions support the color parameter only (for example, dist plot), while others can support both color and palette (for example, bar plot and box plot). Readers can refer to the official documentation to see which parameter is supported.

The following three code excerpts demonstrate the use of the color or palette parameter in a dist plot, bar plot, and box plot:

# Note: Codes related to data preparation and imports are skipped
# for brevity
# Change the color of histogram and KDE line to darkred
ax = sns.distplot(current_bigmac.dollar_price, color="darkred")
plt.show()
current_population = population_df[(population_df.Location == 'United States of America') & 
(population_df.Time == 2017) &
(population_df.Sex != 'Both')]
# Change the color palette of the bar chart to Paired
sns.barplot(x="AgeGrp",y="Value", hue="Sex", palette="Paired", data = current_population)
# Rotate tick labels by 30 degree
plt.setp(plt.gca().get_xticklabels(), rotation=30, horizontalalignment='right')
plt.show()
# Note: Codes related to data preparation and imports are skipped
# for brevity
# Change the color palette of the bar chart to Set2 from color
# brewer library
ax = sns.boxplot(x="population type", y="dollar_price", palette="Set2", data=merged_df2)
plt.show()
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset