r - 使用 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 种不同颜色的其他解决方案。
解决方案
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)
推荐阅读
- android - 如何创建可以从 android 中的并发应用程序访问功能的后台服务?
- csv - 如何使用查询命令将弹性搜索所有记录放入 csv 文件
- python - 关于 O(LogN) 的时间复杂度
- java - weblogic证书导入问题
- python - 在模块末尾分配的变量
- javascript - 如何在 php 中创建干净的 url 从 mysql 获取数据?
- arrays - 致命错误:索引超出范围?但真的吗?
- entity-framework-6 - Entity Framework (v6) Eager-Loading 奇怪的行为 - 'Gotcha'
- javascript - 括号中的正则表达式匹配数(Firefox)
- java - 为什么这加起来是 11 而不是 8?