首页 > 解决方案 > 在不同的情节中,一致的可变颜色

问题描述

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 个解释变量,这似乎超出了颜色 brewer 的限制,因此存在两个问题:

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

先感谢您。

标签: rggplot2plotpca

解决方案


(我假设你已经知道你需要添加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)

情节1

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

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

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)

情节2


推荐阅读