pandas Seaborn 调色板 - 防止颜色回收
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/26301347/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Seaborn palettes - prevent recycling of colors
提问by iayork
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?
Seaborn 允许定义包含多种颜色的调色板,这对于具有多行的图表很有用。但是,当将调色板设置为多色时,只会使用前六种颜色,之后颜色会循环使用,因此很难区分线条。这可以通过显式调用调色板来覆盖,但这并不方便。当定义超过 6 个颜色时,有没有办法强制 Seaborn 当前调色板不回收颜色?
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)


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


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


采纳答案by iayork
Solution (thanks to @tcaswell for the pointer): Set the palette explicitly using all colors:
解决方案(感谢@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)) ;



