在Seaborn中创建一个黑暗的反色调色板

时间:2015-05-07 15:29:25

标签: python python-2.7 seaborn

我正在使用顺序调色板创建一个包含多个绘图的图形,如下所示:

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()

但是,我想颠倒调色板。 The tutorial声明我可以将'_r'添加到调色板名称以反转它,并'_d'使其变为"黑暗"。但我似乎无法一起完成这些操作:'_r_d''_d_r''_rd''_dr'都会产生错误。如何创建一个黑暗的反转调色板?

1 个答案:

答案 0 :(得分:6)

我回答我自己的问题,发布我使用的解决方案的详细信息和解释,因为mwaskom的建议需要调整。使用

with reversed(sns.color_palette('Blues_d', n_colors=n_plots)):

抛出AttributeError: __exit__,我相信因为with语句需要一个__enter____exit__方法的对象,而reversed迭代器并不满足。如果我使用sns.set_palette(reversed(palette))而不是with语句,则忽略绘图中颜色的数量(使用默认值6 - 我不知道为什么),即使遵循颜色方案。要解决此问题,我使用list.reverse()方法:

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()

编辑:discovered在调用n_colors时忽略set_palette参数的原因是因为n_colors参数还必须在该电话中指定。因此,另一种解决方案是:

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()
相关问题