Seaborn调色板 - 防止颜色重复使用

17
Seaborn允许定义包含多种颜色的调色板,对于有许多线条的图表非常有用。然而,当将调色板设置为具有多种颜色的调色板时,仅使用前六种颜色,之后颜色会循环,使得难以区分线条。可以通过显式调用调色板来覆盖此行为,但这并不方便。是否有一种方法可以强制Seaborn当前的调色板在定义了6个以上颜色时不循环使用颜色?
示例:
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


1
这对我来说像是一个 seaborn 的 bug。 - tacaswell
1
其实,我不这么认为:http://web.stanford.edu/~mwaskom/software/seaborn/generated/seaborn.color_palette.html。看起来它正在做它应该做的事情,只是有点烦人。 - tacaswell
1
嗯,我仍然认为它有漏洞。文档中对于n_colors的说明是:“调色板中的颜色数量。如果大于调色板中的颜色数量,则它们将循环。”这意味着如果不大于调色板中的颜色数量,它们将不会循环,但实际上它们仍然会循环。我将编辑问题以说明这一点。 - iayork
我非常确定 set_palette 只是获取正在使用的调色板,而不是实例对象,因此默认情况下会返回一个由6个颜色循环组成的项目。 - tacaswell
你说得对,我现在明白了——它需要在set_palette上显式地使用n_numbers,然后在color_palette上也要使用。 - iayork
1个回答

11

解决方案(感谢@tcaswell的指引):使用所有颜色明确设置调色板:

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

输入图像描述 输入图像描述 输入图像描述 输入图像描述

# 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)) ;

在此输入图片描述


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接