如何在 matplotlib 中扩展调色板?

How to extend the color palette in matplotlib?

我编写了以下函数:

def plot_cumulative_dynamic_auc(risk_score, label, color=None):

    auc, mean_auc = cumulative_dynamic_auc(y_trn, y_test, risk_score, times)
    plt.plot(times, auc, marker="o", color=color, label=label)
    plt.xlabel("days from enrollment")
    plt.ylabel("time-dependent AUC")
    plt.axhline(mean_auc, color=color, linestyle="--")
    plt.legend()

然后是 for 循环:

for i, col in enumerate(num_columns):
    plot_cumulative_dynamic_auc(X_test.iloc[:, i], col, color="C{}".format(i))
    ret = concordance_index_ipcw(y_trn, y_test, X_test.iloc[:, i], tau=times[-1])

由于 for 循环遍历具有 40 个变量的 num_columns,标准调色板仅提供 10 种颜色。但是,我想让每个变量都有自己的颜色。当涉及到变量数量时,有没有一种编码方法也很灵活?

Matplotlib 提供 tab20,这对您的情况来说限制太多。由于你有很多行,一个可能的解决方案是使用一个或多个颜色图。看看 available color maps.

单个颜色图

通过选择合适的色图,我们将有一个不错的能力来理解情节。例如,使用 hsv:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.cm as cm

N = 40 # number of lines
x = np.array([0, 1])
theta = np.linspace(0, np.pi / 2, N)

discr = np.linspace(0, 1, N)
# create N colors from the colormap
colors = cm.hsv(discr)

f, ax = plt.subplots()
for i, t in enumerate(theta):
    ax.plot(x, np.tan(t) * x, color=colors[i])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)

如您所见,第一行和最后一行使用相似的颜色,因此如果颜色图是循环的(例如 hsv),那么限制离散化范围可能是个好主意,例如 discr = np.linspace(0, 0.75, N).

从多个颜色图创建颜色

Matplotlib 提供了许多不同的颜色图。我们可以使用它们来创建颜色组合,例如:

import numpy as np
from matplotlib import pyplot as plt
import matplotlib.cm as cm

# compile a list of colormaps
colormaps = [cm.Reds_r, cm.Blues_r, cm.Greens_r, cm.Purples_r]
N = 40 # number of lines
x = np.array([0, 1])
theta = np.linspace(0, np.pi / 2, N)

# extract the following number of colors for each colormap
n_cols_per_cm = int(np.ceil(N / len(colormaps)))
# discretize the colormap. Note the upper limit of 0.75, so we
# avoid too white-ish colors
discr = np.linspace(0, 0.75, n_cols_per_cm)

# extract the colors
colors = np.zeros((n_cols_per_cm * len(colormaps), 4))
for i, cmap in enumerate(colormaps):
    colors[i * n_cols_per_cm : (i + 1) * n_cols_per_cm, :] = cmap(discr)

f, ax = plt.subplots()
for i, t in enumerate(theta):
    ax.plot(x, np.tan(t) * x, color=colors[i])
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)