首页 > 解决方案 > 使用 ggplot2 进行 R 数据可视化 - 使用 RColorBrewer 为 20 个变量添加颜色

问题描述

我正在尝试使用 ggplot2 可视化数据,并在“描述”中的 20 个类别中添加 20 种不同的颜色。没有颜色,脚本可以完美运行(只有黑色)。但是,无论如何我想添加颜色,它要么保持黑色,要么使用下面的脚本出现以下错误: Error: Aesthetics must be either length 1 or the same as the data (2265723): colour 这应该不是问题,因为“Pastel1”有 255 种颜色,并且我创建了一个长度变量。

数据集(描述有 20 个类别):

chr pos p description
1 445578 0.05 Metabolic
3 659990 0.34 Metabolic
5 789689 0.55 Immunological
6 678599 0.05 BodyStructures
7 97890 0.67 Cardiovascular
2 67899 0.01 Hematological
8 9867647 0.34 Nutritional
3 675890 0.55 Environment
6 799030 0.76 Psychiatric
4 8609000 0.88 Cognitive
6 789900 0.12 Musculoskeletal
3 90907878 0.22 Opthalmological
colourCount = length(unique(dataset$description))
getPalette = colorRampPalette(brewer.pal(9, "Pastel1"))
Nean_PheWAS <- ggplot(dataset, aes(x=description, y=-log(p), colour = getPalette(colourCount))) + 
geom_jitter(mapping=aes(x=as.factor(description), y=-log10(p))) +
theme_classic() + 
theme(axis.text.x = element_blank(), 
panel.grid.minor=element_line(colour = "grey", linetype="dashed"), axis.ticks=element_blank()) + 
labs(color="description", size="Effect size", x="Phenotype Classes", y="log(p-value)") +
geom_hline(yintercept=-log(0.01), color="red", size=1, alpha=0.5)

我也愿意为类别添加 20 种不同颜色的其他解决方案。

标签: rggplot2data-visualization

解决方案


Assuming that you wish to colour by the variable description, you can use the ColorBrewer palette with colourCount number of elements by adding scale_colour_manual(values = getPalette(colourCount)) to the ggplot object. And change colour = description in the aesthetics:

colourCount = length(unique(dataset$description))
getPalette = colorRampPalette(brewer.pal(9, "Pastel1"))
Nean_PheWAS <- ggplot(dataset, aes(x=description, y=-log(p), colour = description)) + 
geom_jitter(mapping=aes(x=as.factor(description), y=-log10(p))) +
theme_classic() + scale_colour_manual(values = getPalette(colourCount)) +
theme(axis.text.x = element_blank(), 
panel.grid.minor=element_line(colour = "grey", linetype="dashed"), axis.ticks=element_blank()) + 
labs(color="description", size="Effect size", x="Phenotype Classes", y="log(p-value)") +
geom_hline(yintercept=-log(0.01), color="red", size=1, alpha=0.5)

推荐阅读