gpt4 book ai didi

r - 在 ggplot 中为 ggrepel 设置限制

转载 作者:行者123 更新时间:2023-12-04 13:15:14 25 4
gpt4 key购买 nike

我有一个 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))

enter image description here

我正在尝试在图表中为标签设置限制,以便它们始终高于 2.5 或低于 -2.5,并且位于 30 的右侧或 0 的左侧。感谢您的帮助!

最佳答案

查看 documentation对于 ggrepel,您似乎无法指定“标签禁区”,而这实际上正是您要查找的内容。最好的选择是使用 xlimylim 来定义部分,然后相应地“分割”您的数据以创建“标签禁区”的错觉。

为此,我将您的数据分成了象限:

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))

这给了你这个:

enter image description here

在我看来有点像。为了更好地获得您可能正在寻找的效果,我将数据分成高于和低于平均值的 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))

enter image description here

你可以做同样的事情切换轴(根据 x 值拆分数据),但我认为它在这里会更好,因为数据分布在更大的 x 轴区域。

关于r - 在 ggplot 中为 ggrepel 设置限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61120196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com