本文介绍了我该如何切割"geom_curve"绘制的曲线,以使其不与"ggplot2"中"geom_text"绘制的标签重叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个df
,其中包含类型为var
和link
的元素.我想使用geom_text
将元素var
绘制为文本标签,使用geom_curve
将元素links
绘制为箭头.问题是links
对标签进行过度绘制,而我希望它们在标签旁边开始和停止.
I have a df
containing elements of type var
and link
. I want to plot the elements var
as text label using geom_text
and the links
as arrows using geom_curve
. The problem is, that the links
overplot the labels whereas I want them to start and stop just beside the labels.
我所拥有的:
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
当我绘制它时,它看起来如下:
When I plot it it looks as follows:
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")
我期望的是:
我该如何实现?
这是我的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")
这是我做的手动调整,以绘制预期的输出:
And here is the manual tweak I did to plot my expected output:
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")
推荐答案
- 计算
to_x
和from_y
的适当偏移量. - 更改几何的顺序,以使
geom_text
呈现在堆栈的最后(即顶部)
- Calculate an appropriate offset for the
to_x
andfrom_y
. - Change the order of your geoms so
geom_text
is rendered last (i.e. top) in the stack
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))
这篇关于我该如何切割"geom_curve"绘制的曲线,以使其不与"ggplot2"中"geom_text"绘制的标签重叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!