根据最新的更新,ggrepel现在支持hjust和vjust。根据文档,使用这个应该对齐所有的标签。但是,我无法使标签对齐,如下所示

我试过了
library(tidyverse)
library(ggrepel)
df <- data.frame(x=seq(1:5), y=seq(1:5), label=letters[seq(1:5)])
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
hjust=0,
direction='y',
nudge_x=0.1,
segment.size=0.2) +
geom_smooth(method='lm')如何对齐这些标签?
编辑
我要补充的是,它不仅仅是让标签对齐,而且让它们彼此靠近,有不同长度的连接器来方便这一点。
发布于 2017-11-26 03:01:05
首先,据我所知,这只能在开发版本中使用。所以你需要从github安装它:
devtools::install_github("slowkow/ggrepel")其次,我认为这只适用于具有相同x值(对于hjust)或y值(对于vjust)的数据点。
示例:
library(tidyverse)
library(ggrepel)
df <- data.frame(x=seq(1:5), y=3, label=letters[seq(1:5)])
# not aligned
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
# vjust=0,
direction='y',
nudge_x=0.1,
segment.size=0.2) +
geom_smooth(method='lm')

# aligned bottom
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
vjust=0,
direction='y',
nudge_x=0.1,
segment.size=0.2) +
geom_smooth(method='lm')

# aligned top
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
vjust=1,
direction='y',
nudge_x=0.1,
segment.size=0.2) +
geom_smooth(method='lm')

发布于 2017-11-26 02:24:33
基于文档(https://cran.r-project.org/web/packages/ggrepel/vignettes/ggrepel.html),在CRAN上的当前版本(0.7.0)中不支持hjust。
此外,您的direction、nudge_x和nudge_y似乎没有关联。
我将您的代码稍微更改为以下三个版本。
direction = 'y' 和 nudge_y = 0.1
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
direction = 'y',
nudge_y = 0.1,
segment.size=0.2) +
geom_smooth(method='lm')

direction = 'x' 和 nudge_x = 0.1
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
direction = 'x',
nudge_x = 0.1,
segment.size=0.2) +
geom_smooth(method='lm')

direction = 'both'**,** nudge_x = 0.1**,和** nudge_y = 0.3
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
direction = 'both',
nudge_x = 0.1,
nudge_y = 0.3,
segment.size=0.2) +
geom_smooth(method='lm')

好像起作用了。我注意到的唯一一点是,由于e和y-axis的局限性,标签y-axis似乎受到限制,因此您可能希望按如下方式进一步展开这个轴。
ggplot(df, aes(x=x, y=y)) +
geom_point() +
geom_text_repel(aes(label=label),
force=1, point.padding=unit(1,'lines'),
direction = 'y',
nudge_y = 0.1,
segment.size=0.2) +
geom_smooth(method='lm') +
scale_y_continuous(limits = c(1, 5.5))

发布于 2017-11-26 03:38:13
不知道你的目标到底是什么。如果你想要所有的标签在一边,它可能更容易只是手工绘制他们,而不是使用ggrepel。
df <- data.frame(x=seq(1:5), y=seq(1:5), label=letters[seq(1:5)])
ggplot(df, aes(x = x, y = y)) +
geom_point() +
geom_text(aes(x = max(x) + 0.1, y = y, label=label), hjust = 0, vjust = 0.5) +
geom_segment(aes(x = x + 0.04, xend = max(x) + 0.06, y = y, yend = y), size = 0.2) +
geom_smooth(method='lm')

https://stackoverflow.com/questions/47492191
复制相似问题