Ger*_*ard 5 label r ggplot2 ggrepel
好的,所以我有一个包含 2 个变量 X 和 Y 以及一个 ID 变量的数据集。我使用以下代码创建了一个完整的情节:
ggplot(data = X_Y) +
geom_point(mapping = aes(x = X, y = Y))+
geom_text_repel(mapping = aes(x = X, y = Y, label = ID))+
xlim(0,100)+
ylim(0,100)
Run Code Online (Sandbox Code Playgroud)
我现在希望创建一些单独的图,一次只显示一个带有标签的数据点。
现在我可以只使用 geom_label 而不排斥和轻推标签来得到这个:

虽然这个情节没问题,但我想知道是否有任何方法可以保持将标签连接到点的线条,就像 ggrepel 所做的那样......
编辑
从第一个建议开始,当我尝试在只选择一个案例的情况下使用排斥时,我得到以下图:
ggplot(data = X_Y) +
geom_point(aes(x = X[4], y = Y[4]))+
geom_label_repel(aes(x = X[4], y = Y[4]),
label = "You are here",
min.segment.length = unit(0, 'lines'),
nudge_y = 6)+
labs(x = "X",y = "Y",title = "mytitle")+
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 100))
Run Code Online (Sandbox Code Playgroud)
解决
弄清楚了!我需要在 ggplot() 中将我的数据指定为 X 和 Y 变量并限制为感兴趣的行。
像这样:
ggplot(data = X_Y[4,c(3,4)) +
geom_point(aes(x = X, y = Y))+
geom_label_repel(aes(x = X, y = Y),
label = "You are here",
min.segment.length = unit(0, 'lines'),
nudge_y = 6)+
labs(x = "X",y = "Y",title = "mytitle")+
scale_x_continuous(limits = c(0, 100)) +
scale_y_continuous(limits = c(0, 100))
Run Code Online (Sandbox Code Playgroud)
您当然仍然可以使用geom_label_repel,即使只有一个点。为确保绘制了一个段,请调整min.segment.lengtharg。此 arg 设置从点到标签的最小距离以绘制线段,将其设置为unit(0, 'lines')确保绘制每个线段:
library(ggplot2)
library(ggrepel)
ggplot(data.frame(x = 2, y = 3)) +
geom_point(aes(x, y)) +
geom_label_repel(aes(x, y),
label = 'You are here',
min.segment.length = unit(0, 'lines'),
nudge_y = .2) +
scale_x_continuous(limits = c(0, 3)) +
scale_y_continuous(limits = c(0, 4))
Run Code Online (Sandbox Code Playgroud)

| 归档时间: |
|
| 查看次数: |
5649 次 |
| 最近记录: |