在图表中的事实上,一致的变量颜色

问题描述 投票:1回答:1

我正在尝试使用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个解释变量,似乎高于颜色酿造者的限制,所以有2个问题:

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

先感谢您。

r ggplot2 plot pca
1个回答
2
投票

(我假设您已经知道需要将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)

plot1

我们可以使用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()

palette

在每个图表上使用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)

plot2

© www.soinside.com 2019 - 2024. All rights reserved.