我正在尝试使用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个问题:
先感谢您。
(我假设您已经知道需要将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)
我们可以使用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)