使用 ggplot2 进行 R 数据可视化 - 使用 RColorBrewer 为 20 个变量添加颜色

R data visualization with ggplot2 - adding colors to 20 variables with RColorBrewer

我正在尝试使用 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 种不同的颜色。

假设您希望通过变量 description 着色,您可以通过将 scale_colour_manual(values = getPalette(colourCount)) 添加到 ggplot 对象来使用具有 colourCount 个元素的 ColorBrewer 调色板。并在美学上改变colour = description

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)