我撰寫了以下函式:
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 種顏色。但是,我想讓每個變數都有自己的顏色。當涉及到變數的數量時,有沒有辦法對其進行編碼也很靈活?
uj5u.com熱心網友回復:
Matplotlib 提供tab20,這對您的情況來說太嚴格了。由于您有很多行,一個可能的解決方案是使用顏色圖,或者不止一個。看看
如您所見,第一行和最后一行使用相似的顏色,因此如果顏色圖是回圈的(例如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)

轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/473884.html
標籤:Python matplotlib 颜色
