【问题标题】:Add a legend for a geom_text layer to explain labels为 geom_text 图层添加图例以解释标签
【发布时间】:2022-08-19 16:11:58
【问题描述】:

考虑以下示例,其中制作了一个散点图,并且只有“重要”点被着色和标记。

genes <- read.table(\"https://gist.githubusercontent.com/stephenturner/806e31fce55a8b7175af/raw/1a507c4c3f9f1baaa3a69187223ff3d3050628d4/results.txt\", header = TRUE)
genes$Significant <- ifelse(genes$padj < 0.05, \"FDR < 0.05\", \"Not Sig\")
ggplot(genes, aes(x = log2FoldChange, y = -log10(pvalue))) +
  geom_point(aes(color = Significant)) +
  scale_color_manual(values = c(\"red\", \"grey\")) +
  theme_bw(base_size = 12) + theme(legend.position = \"bottom\") +
  geom_text_repel(
    data = subset(genes, padj < 0.05),
    aes(label = Gene),
    size = 5,
    box.padding = unit(0.35, \"lines\"),
    point.padding = unit(0.3, \"lines\")
  )

它产生以下情节

现在想象一下,标签实际上是首字母缩略词,并且它们有一个真正的全长名称(例如,\"DOK6\" 是 \"Duo Ocarino Kayne 6\" 的首字母缩写词)。是否可以在图中添加一个图例,其中键是图中使用的标签,条目是标签的全长名称?

标签: r ggplot2 legend


【解决方案1】:

首先,我为另一个图例添加了Gene2,它只显示了重要的Gene。\

接下来,Gene2 作为fill 添加到aes。 (只有color 会影响geom_point 上点的颜色)。\

最后,为第二个图例添加了scale_fill_discrete。您需要做的只是在Full names here 处注释全长名称列。

genes$Gene2 <-ifelse(genes$padj<0.05, genes$Gene, NA)
ggplot(genes, aes(x = log2FoldChange, y = -log10(pvalue),
                  fill=Gene2)) +
  geom_point(aes(color = Significant)) +
  scale_color_manual(values = c("red", "grey")) +
  theme_bw(base_size = 12) + theme(legend.position = "bottom") +
  geom_text_repel(
    data = subset(genes, padj < 0.05),
    aes(label = Gene),
    size = 5,
    box.padding = unit(0.35, "lines"),
    point.padding = unit(0.3, "lines")
  ) +
  scale_fill_discrete(labels=paste0(genes$Gene,': ',' Full names here'),
                      name='Significant genes') +
  theme(legend.position = 'right')

输出

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 2019-01-22
    • 2012-05-09
    • 2016-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多