python - 将 seaborn.palplot 轴添加到现有图形以可视化不同的调色板
问题描述
将 seaborn 图形添加到子图通常通过在创建图形时传递“ax”来完成。例如:
sns.kdeplot(x, y, cmap=cmap, shade=True, cut=5, ax=ax)
但是,此方法不适用于seaborn.palplot,它可以可视化 seaborn 调色板。我的目标是创建一个不同调色板的图形,用于可扩展的颜色比较和演示。这张图片大致显示了我正在尝试创建的图 [ source ]。
一个可能相关的答案描述了一种创建海底图形并将轴复制到另一个图形的方法。我无法将此方法应用于 palplot 图形,并且想知道是否有一种快速方法可以将它们强制到现有图形中。
这是我的最小工作示例,现在仍然生成单独的数字。
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
fig1 = plt.figure()
length, n_colors = 12, 50 # amount of subplots and colors per subplot
start_colors = np.linspace(0, 3, length)
for i, start_color in enumerate(start_colors):
ax = fig1.add_subplot(length, 1, i + 1)
colors = sns.cubehelix_palette(n_colors=n_colors, start=start_color,
rot=0, light=0.4, dark=0.8)
sns.palplot(colors)
plt.show(fig1)
最终,为了使绘图更具信息性,最好打印存储在颜色(类似列表)中的 RGB 值,均匀分布在 palplots 上,但我不知道这是否容易实现,因为绘图方式不寻常在 palplot 中。
任何帮助将不胜感激!
解决方案
正如您可能已经发现的那样,palplot 函数的文档很少,但我直接从seaborn github repo中提取:
def palplot(pal, size=1):
"""Plot the values in a color palette as a horizontal array.
Parameters
----------
pal : sequence of matplotlib colors
colors, i.e. as returned by seaborn.color_palette()
size :
scaling factor for size of plot
"""
n = len(pal)
f, ax = plt.subplots(1, 1, figsize=(n * size, size))
ax.imshow(np.arange(n).reshape(1, n),
cmap=mpl.colors.ListedColormap(list(pal)),
interpolation="nearest", aspect="auto")
ax.set_xticks(np.arange(n) - .5)
ax.set_yticks([-.5, .5])
# Ensure nice border between colors
ax.set_xticklabels(["" for _ in range(n)])
# The proper way to set no ticks
ax.yaxis.set_major_locator(ticker.NullLocator())
因此,它不会返回任何轴或图形对象,也不会允许您指定要写入的轴对象。您可以通过添加 ax 参数和条件来制作自己的,如下所示,以防未提供。根据上下文,您可能还需要包含的导入。
def my_palplot(pal, size=1, ax=None):
"""Plot the values in a color palette as a horizontal array.
Parameters
----------
pal : sequence of matplotlib colors
colors, i.e. as returned by seaborn.color_palette()
size :
scaling factor for size of plot
ax :
an existing axes to use
"""
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
n = len(pal)
if ax is None:
f, ax = plt.subplots(1, 1, figsize=(n * size, size))
ax.imshow(np.arange(n).reshape(1, n),
cmap=mpl.colors.ListedColormap(list(pal)),
interpolation="nearest", aspect="auto")
ax.set_xticks(np.arange(n) - .5)
ax.set_yticks([-.5, .5])
# Ensure nice border between colors
ax.set_xticklabels(["" for _ in range(n)])
# The proper way to set no ticks
ax.yaxis.set_major_locator(ticker.NullLocator())
当您包含“ax”参数时,此函数应该像您期望的那样工作。要在您的示例中实现这一点:
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
fig1 = plt.figure()
length, n_colors = 12, 50 # amount of subplots and colors per subplot
start_colors = np.linspace(0, 3, length)
for i, start_color in enumerate(start_colors):
ax = fig1.add_subplot(length, 1, i + 1)
colors = sns.cubehelix_palette(
n_colors=n_colors, start=start_color, rot=0, light=0.4, dark=0.8
)
my_palplot(colors, ax=ax)
plt.show(fig1)