我有一个包含类似如下数据的ggplot图:
data <- data.frame(x = c(1:30),
y = rnorm(30, 0, 1),
z = rep(c("A", "B", "C"), 10))
ggplot(data = data, aes(x = x, y = y, group = z, color = z, label = z)) +
geom_point() +
geom_label_repel(aes(label = z), force = 1, segment.alpha = .5, box.padding = 1, xlim = c(-5, 35), ylim = c(-5, 5)) +
scale_x_continuous(limits = c(-5, 35)) +
scale_y_continuous(limits = c(-5, 5))

我试图在图中为标签设置限制,使它们始终高于2.5或低于-2.5,并且要么位于30的右侧,要么位于0的左侧。谢谢你的帮助!
发布于 2020-04-09 20:56:56
查看ggrepel的documentation,看起来您不能指定一个“标签隔离区”,这实际上就是您正在寻找的。最好的选择是使用xlim和ylim来定义区段,然后相应地“区段”您的数据,以创建“标签隔离区”的错觉。
为此,我将您的数据分解为象限:
ggplot(data = data, aes(x = x, y = y, group = z, color = z, label = z)) +
geom_point() +
geom_label_repel(data=subset(data, x<15 & y<0),
segment.alpha = .5, xlim = c(-5, 0), ylim = c(-5, -2.5)) +
geom_label_repel(data=subset(data, x<15 & y>0),
segment.alpha = .5, xlim = c(-5, 0), ylim = c(2.5, 5)) +
geom_label_repel(data=subset(data, x>15 & y>0),
segment.alpha = .5, xlim = c(30, 35), ylim = c(2.5, 5)) +
geom_label_repel(data=subset(data, x>15 & y<0),
segment.alpha = .5, xlim = c(30, 35), ylim = c(-5, -2.5)) +
scale_x_continuous(limits = c(-5, 35)) +
scale_y_continuous(limits = c(-5, 5))这就给了你这个:

在我看来,有点新潮。为了更好地获得您可能正在寻找的效果,我只需将数据划分为平均值上下的y值,并让ggrepel适当地将它们分布在x轴上。我使用force=参数将它们“推”到x轴上:
ggplot(data = data, aes(x = x, y = y, group = z, color = z, label = z)) +
+ geom_point() +
geom_label_repel(data=subset(data, y<0), force=25,
segment.alpha = .5, ylim = c(-5, -2.5)) +
geom_label_repel(data=subset(data, y>0), force=25,
segment.alpha = .5, ylim = c(2.5, 5)) +
scale_x_continuous(limits = c(-5, 35)) +
scale_y_continuous(limits = c(-5, 5))

您可以做相同的事情切换轴(根据x值拆分数据),但我认为它在这里会更好,因为数据分布在更大的x轴区域上。
https://stackoverflow.com/questions/61120196
复制相似问题