在ggplot2中使用ggrepel

4

我有一个geom_gene_arrow图表,我需要使用ggrepel来防止标签重叠。不幸的是,我无法让它正常工作,并且会出现错误,提示“找不到函数”geom_text_repel“'

只使用geom_text的可行示例:

> ggplot(data, aes(xmin = start, xmax = end, y = genome, fill = colour, forward = direction)) +
     geom_gene_arrow() +
     geom_text(aes(x = end - ((end-start)/2), y = 1.2, label = gene, angle=90)) +
     facet_wrap(~ genome, scales = "free", ncol = 1) +
     theme_void()+
     xlab("")

随着引入geom_text_repel,它失败了。

> ggplot(data, aes(xmin = start, xmax = end, y = genome, fill = colour, forward = direction)) +
     geom_gene_arrow() +
     geom_text_repel(aes(x = end - ((end-start)/2), y = 1.2, label = gene, angle=90)) +
     facet_wrap(~ genome, scales = "free", ncol = 1) +
     theme_void()+
     xlab("")

示例数据:

genome start end gene function colour direction
A 11638 12786 fadA6 ringdegradation green, -1
A 12798 13454 fadE30 cleavage, blue 1
A 13529 14341 fadD3 ringdegradation green -1

任何关于我做错的事情的洞察都非常感激!


你是否已经加载了 ggrepel?此外,在你的 ggplot 代码中,提到了 startendgenome 变量,但这些变量在你的示例中并不存在。你能否提供一个可重现的数据集示例?(请按照此教程操作:https://dev59.com/eG025IYBdhLWcg3whGSx) - dc37
抱歉!我刚刚添加了缺失的列。 - Lauren
是的,我也加载了ggrepel,并且它显示已经成功安装。 - Lauren
奇怪...当你安装ggrepel时,你没有注意到installation of package ‘ggrepel'had non-zero exit status的错误吗?一个函数未找到的常见错误是未加载包(例如在运行代码之前执行library(ggrepel))。 - dc37
我刚刚发现错误了 - 我很惭愧地承认,我在导入包之前没有写上library(ggrepel)... 哈哈。非常感谢你的帮助。 - Lauren
1个回答

3

我认为您需要加载ggrepel包。在我的会话中,我没有任何问题可以得到这个图形:

library(ggplot2)
library(ggrepel)
library(gggenes)
ggplot(data, aes(xmin = start, xmax = end, y = genome, fill = colour, forward = direction)) +
  geom_gene_arrow(arrowhead_height = unit(4, "mm"), 
                  arrowhead_width = unit(2, "mm"), arrow_body_height = unit(4, "mm")) +
  geom_text_repel(aes(x = end - ((end-start)/2), y = 1.2, label = gene, angle=90)) +
  facet_wrap(~ genome, scales = "free", ncol = 1) +
  theme_void()+
  xlab("")

enter image description here

这里使用 geom_text

library(ggplot2)
  library(ggrepel)
  library(gggenes)
  ggplot(data, aes(xmin = start, xmax = end, y = genome, fill = colour, forward = direction)) +
    geom_gene_arrow(arrowhead_height = unit(4, "mm"), 
                    arrowhead_width = unit(2, "mm"), arrow_body_height = unit(4, "mm")) +
    geom_text(aes(x = end - ((end-start)/2), y = 1.2, label = gene, angle=90)) +
    facet_wrap(~ genome, scales = "free", ncol = 1) +
    theme_void()+
    xlab("")

enter image description here

您可以看到在第一个图中,geom_text_repel的作用是标签与箭头的一半并不完全对齐。 可重现的示例
structure(list(genome = c("A", "A", "A"), start = c(11638L, 12798L, 
13529L), end = c(12786L, 13454L, 14341L), gene = c("fadA6", "fadE30", 
"fadD3"), `function` = c("ringdegradation", "cleavage,", "ringdegradation"
), colour = c("green,", "blue", "green"), direction = c(-1L, 
1L, -1L)), row.names = c(NA, -3L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x56276b4f1350>)

你说得对!我已经安装了这个包,但是在我的导言部分中没有library(ggrepel)... - Lauren

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接