如何切割`geom_curve`绘制的曲线,以便它们不与`ggplot2`中`geom_text`绘制的标签重叠?

问题描述 投票:2回答:1

我有一个df包含varlink类型的元素。我想使用var将元素geom_text作为文本标签绘制,使用linksgeom_curve作为箭头绘制。问题是,links过度标记标签,而我希望它们在标签旁边开始和停止。


是)我有的:

  type   x    y                    label from_x from_y to_x to_y
1 link  NA   NA                     <NA>    608   -229  460 -276
2 link  NA   NA                     <NA>    428   -274  570 -226
3  var 610 -226 accomplishments per week    608   -229  460   NA
4  var 426 -276    hours worked per week    428   -274  570   NA

当我绘制它时,它看起来如下:

ggplot(df) + geom_text(aes(x, y, label = label)) + geom_curve(aes(x = 
from_x,y = from_y,xend = to_x, yend = to_y), curvature = -.3, arrow = arrow(length = unit(0.03, "npc")), color = "red")

enter image description here


我的期望是:

enter image description here

我怎样才能做到这一点?


这是我的df

df <- structure(list(type = structure(c(1L, 1L, 2L, 2L), .Label = c("link", 
"var"), class = "factor"), x = c(NA, NA, 610, 426), y = c(NA, 
NA, -226, -276), label = c(NA, NA, "accomplishments per week", 
"hours worked per week"), from_x = c(610, 426, NA, NA), from_y = c(-226, 
-276, NA, NA), to_x = c(426, 610, NA, NA), to_y = c(-276, -226, 
NA, NA)), .Names = c("type", "x", "y", "label", "from_x", "from_y", 
"to_x", "to_y"), row.names = c(NA, -4L), class = "data.frame")

这是我用来绘制预期输出的手动调整:

df$from_x <- c(608, 428)
df$from_y <- c(-229, -274)
df$to_x <- c(460, 570)

ggplot(df) + geom_text(aes(x, y, label = label)) + geom_curve(aes(x = from_x,y = from_y,xend = to_x, yend = to_y), curvature = -.3, arrow = arrow(length = unit(0.03, "npc")), color = "red")
r ggplot2
1个回答
1
投票
  1. 计算to_xfrom_y的适当偏移量。
  2. 更改geoms的顺序,使geom_text在堆栈中最后(即顶部)呈现
df <-
  df %>%
  mutate(
    to_xoffset = if_else(to_y > -250, to_x - 25, NA_real_),
    to_xoffset = if_else(to_y < -250, to_x + 25, to_xoffset),

    from_yoffset = if_else(from_x < 525, from_y + 2, NA_real_),
    from_yoffset = if_else(from_x > 525, from_y - 2, from_yoffset)
  )

ggplot(df) + 
  geom_curve(aes(x = from_x,y = from_yoffset ,xend = to_xoffset, yend = to_y), curvature = -.3, arrow = arrow(length = unit(0.03, "npc")), color = "red") +
  geom_text(aes(x, y, label = label))
© www.soinside.com 2019 - 2024. All rights reserved.