r - 对齐单个ggrepel标签内的文本行

标签 r ggplot2 ggrepel

我有一个图,其中用多行ggrepel标签标记元素。我想在其中一些中右对齐,在其他一些中左对齐。参见示例:

p <- ggplot() +
  coord_cartesian(xlim=c(0,1), ylim=c(0,1)) +
  theme_void()
p

labelInfo <- data.frame(x=c(0.45,0.55), y=c(0.5,0.5), 
                        g=c("I'd like very much to be\nright justified","And I'd like to be\nleft justified"))

p + geom_label_repel(data=labelInfo, aes(x,y,label=g), 
                     box.padding = 0.5, point.padding = 0.75, 
                     nudge_x = c(-0.05,0.05), nudge_y = 0, direction="x",
                     arrow=arrow(length=unit(2,"mm"), ends="last", type="closed"))

enter image description here

如果我使用ggplot2注释执行此操作,则将这样做,这样就产生了我想要的左右对齐方式:
p + annotate("text", label="I'd like very much to be\nright justified", x=0.45, y=0.5, hjust=1) +
  annotate("text", label="And I'd like to be\nleft justified", x=0.55, y=0.5, hjust=0)

enter image description here

如何使用ggrepel标签实现这一目标?

谢谢!

最佳答案

现在已在ggrepel的开发版本(版本0.8.1.9000)中解决了此问题。

library(ggplot2)
devtools::install_github("slowkow/ggrepel") 

p <- ggplot() +
  coord_cartesian(xlim=c(0,1), ylim=c(0,1)) +
  theme_void()
p

labelInfo <- data.frame(x=c(0.45,0.55), y=c(0.5,0.5), 
                        g=c("I'd like very much to be\nright justified","And I'd like to be\nleft justified"))

p + geom_label_repel(data=labelInfo, aes(x,y,label=g), hjust=c(1,0),
                     box.padding = 0.5, point.padding = 0.75, 
                     nudge_x = c(-0.05,0.05), nudge_y = 0, direction="x",
                     arrow=arrow(length=unit(2,"mm"), ends="last", type="closed"))

enter image description here

关于r - 对齐单个ggrepel标签内的文本行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54448262/

相关文章:

R 中的正则表达式限制一个术语 AND 另一个不是 OR 另一个

r - 在 R 中生成由节点函数递归定义的 K-Nary 树

删除ggplot图例中的重复标签

r - 观察事件有两个条件

r - 在 ggrepel 标签中使用plotmath

r - GGPLOT 将堆叠条形图中的标签与数据子集对齐

r - 使用 ggplot2 的 Github 版本运行 ggrepel 时,zero_range() 出现错误

r - 向聚类散点图 (tSNE) 添加文本注释

r - 如何将循环的结果存储到变量中?在R中