r - 在不同的情节中,一致的可变颜色
问题描述
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 的限制,因此存在两个问题:
- 如何保持一致的配色方案
- 能够使用 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)
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)
推荐阅读
- google-maps - 单击多边形时显示信息窗口
- android - 如何更改工具栏中图标的颜色?
- knockout.js - KnockoutJS 获取 Select 的文本和值
- javascript - 是否可以在 JMES 路径中获取具有最大值属性的所有对象?
- google-apps-script - 我正在尝试获取有关如何根据单元格值将一行移动(或复制)到另一个工作簿的指导?
- javascript - 如何在手机浏览器中显示谷歌相册?
- python - 在python中逐行将数据写入csv文件
- angular - 带有映射的孩子的Angular 8 http子请求
- javascript - 单击 asp:linkbutton 时如何使用 data-id 填充隐藏字段
- php - 尝试模拟 Laravel Socialite Google Login 进行集成测试