【问题标题】:Set limits within ggplot for ggrepel在ggplot中为ggrepel设置限制
【发布时间】:2020-04-09 11:32:25
【问题描述】:

我有一个 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 的左侧。感谢您的帮助!

【问题讨论】:

    标签: r ggplot2 limit ggrepel


    【解决方案1】:

    查看ggrepeldocumentation,您似乎无法指定“标签禁区”,这实际上就是您要查找的内容。最好的选择是使用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))
    

    这给了你这个:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2021-03-06
      • 1970-01-01
      • 2018-11-01
      • 1970-01-01
      相关资源
      最近更新 更多