Creating a dark, reversed color palette in Seaborn
I'm answering my own question to post the details and explanation of the solution I used, because mwaskom's suggestion required a tweak. Using
with reversed(sns.color_palette('Blues_d', n_colors=n_plots)):
throws AttributeError: __exit__
, I believe because the with statement requires an object with __enter__
and __exit__
methods, which the reversed
iterator doesn't satisfy. If I use sns.set_palette(reversed(palette))
instead of a with statement, the number of colors in the plot is ignored (the default of 6 is used - I have no idea why) even though the color scheme is obeyed. To solve this, I use list.reverse()
method:
figure = plt.figure(1)
x = range(1, 200)
n_plots = 10
palette = sns.color_palette("Blues_d", n_colors=n_plots)
palette.reverse()
with palette:
for offset in range(n_plots):
plt.plot(x, [offset + math.sin(float(i) / 10) for i in range(len(x))])
figure.show()
Edit: I discovered that the reason the n_colors
argument was ignored in the call to set_palette
was because the n_colors
argument must also be specified in that call. Another solution is therefore:
figure = plt.figure(1)
x = range(1, 200)
n_plots = 10
sns.set_palette(reversed(sns.color_palette("Blues_d", n_plots)), n_plots)
for offset in range(n_plots):
plt.plot(x, [offset + math.sin(float(i) / 10) for i in range(len(x))])
figure.show()
Related videos on Youtube
Ninjakannon
Tech lead with specialisms in platform building, web dev, FinTech & machine learning. Mostly coding in Python and JavaScript/TypeScript/React. Experienced in technical leadership including technical product and project management. The future is platforms.
Updated on September 16, 2022Comments
-
Ninjakannon over 1 year
I am creating a figure that contains several plots using a sequential palette like so:
import matplotlib.pyplot as plt import seaborn as sns import math figure = plt.figure(1) x = range(1, 200) n_plots = 10 with sns.color_palette('Blues_d', n_colors=n_plots): for offset in range(n_plots): plt.plot(x, [offset + math.sin(float(i) / 10) for i in range(len(x))]) figure.show()
However, I would like to reverse the color palette. The tutorial states that I can add
'_r'
to a palette name to reverse it and'_d'
to make it "dark". But I do not appear to be able to do these together:'_r_d'
,'_d_r'
,'_rd'
and'_dr'
all produce errors. How can I create a dark, reversed palette?-
mwaskom almost 9 yearsPalettes are just lists, so you can always use the
reversed()
function.
-