跨地块的 factoextra 一致的可变颜色

Consistent variable colours in factoextra across plots

我试图在使用 factoextra 库绘制 PCA 结果时使我的绘图具有一致的可变颜色。下面的可重现示例:

data("decathlon2")
df <- decathlon2[1:23, 1:10]
library("FactoMineR")
res.pca <- PCA(df,  graph = FALSE)
get_eig(res.pca)

# Contributions of variables to PC1
fviz_contrib(res.pca, choice = "var", axes = 1, top = 10)
# Contributions of variables to PC2
fviz_contrib(res.pca, choice = "var", axes = 2, top = 10)

我希望 PC1 和 PC2 的绘图有一个包含 10 种颜色的调色板,该调色板在绘图中是相同的(即 x100m 在两个绘图中都是红色)。然而,在我的实际数据集中,我有 15 个解释变量,这似乎超出了 color brewer 的限制,所以有 2 个问题:

  1. 如何保持一致的配色方案
  2. 能够使用15种颜色

提前致谢。

(我假设您已经知道需要将 fill = "name" 添加到 fviz_contrib() 调用;否则条形将默认为 fill = "steelblue"。)

您可以手动定义调色板,使每个变量对应相同的颜色。

为了使用问题中的示例模拟问题,假设我们只想显示前 7 个,当总共有 10 个变量时:

# naive way with 7-color palette applied to different variables
fviz_contrib(res.pca, choice = "var", fill = "name", color = "black", axes = 1, top = 7)
fviz_contrib(res.pca, choice = "var", fill = "name", color = "black", axes = 2, top = 7)

我们可以使用 scales 包中的 hue_pal() 创建一个调色板,用于 10 种不同的颜色(df 的每一列一个)。

(您还可以使用基础 grDevices 包中的 rainbow() / heat.colors() 等调色板。我发现它们的默认颜色范围是不过,相当强烈,对于条形图来说往往过于刺眼。)

mypalette <- scales::hue_pal()(ncol(df))
names(mypalette) <- colnames(df)

# optional: see what each color corresponds to
ggplot(data.frame(x = names(mypalette),
                  y = 1,
                  fill = mypalette)) +
  geom_tile(aes(x = x, y = y, fill = fill), color = "black") +
  scale_fill_identity() +
  coord_equal()

在每个图表上使用 scale_fill_manual() 和自定义调色板:

fviz_contrib(res.pca, choice = "var", fill = "name", color = "black", axes = 1, top = 7) +
  scale_fill_manual(values = mypalette)
fviz_contrib(res.pca, choice = "var", fill = "name", color = "black", axes = 2, top = 7) +
  scale_fill_manual(values = mypalette)