使用 ggplot 创建一个西北箭头
Create a North-West arrow with ggplot
我正在使用 annotation_custom
制作带箭头的自定义图例。
不幸的是,所有箭头似乎都有一个向下的角度(指向西南或东北),我正在努力制作一个向上的箭头(指向西北)。
这是一个可重现的例子:
library(ggplot2)
library(grid)
x=ggplot() +
geom_blank() +
geom_rect(aes(xmin=1, xmax=2,
ymin=1, ymax=2)) +
coord_fixed(clip="off") #a plain old nice grey rectangle
my_arrow = linesGrob(arrow=arrow(type="open", ends="first", length=unit(4,"mm")))
x + annotation_custom(my_arrow, xmin=1.5,xmax=2.2, ymin=1.5,ymax=1.25) #South-West :-)
x + annotation_custom(my_arrow, xmin=1.5,xmax=2.2, ymin=1.25,ymax=1.5) #Also South-West :-(
如何构造这样的箭头?
annotation_custom
似乎与从矩形或图像中获得的最小和最大坐标相关联。为了使箭头有意义,它需要一些东西来解释为方向。我正在切换到 annotate
使用分段几何,并保存箭头以供重用。
my_arrow <- arrow(type = "open", ends = "first", length = unit(4, "mm"))
x +
annotate("segment", x = 1.5, xend = 2.2, y = 1.5, yend = 1.25, arrow = my_arrow) +
annotate("segment", x = 1.5, xend = 2.2, y = 1.25, yend = 1.5, arrow = my_arrow)
由于 annotate
没有 data
参数,您不能 (AFAIK) 使用 aes
映射数据框变量,但您可以给它向量以收紧一次通话。
x +
annotate("segment", x = 1.5, xend = 2.2, y = c(1.5, 1.25), yend = c(1.25, 1.5), arrow = my_arrow)
# same output
编辑添加: 根据评论,将线段坐标放在数据框中可能有意义,这样您也可以参考它们来放置标签。
coords <- tibble::tribble(
~x, ~xend, ~y, ~yend, ~lbl,
1.5, 2.2, 1.5, 1.25, "Still a square",
1.5, 2.2, 1.25, 1.5, "This is a square"
)
x +
annotate("segment", x = coords$x, xend = coords$xend, y = coords$y, yend = coords$yend, arrow = my_arrow) +
geom_text(aes(label = lbl, x = xend, y = yend), data = coords, hjust = 0)
我正在使用 annotation_custom
制作带箭头的自定义图例。
不幸的是,所有箭头似乎都有一个向下的角度(指向西南或东北),我正在努力制作一个向上的箭头(指向西北)。
这是一个可重现的例子:
library(ggplot2)
library(grid)
x=ggplot() +
geom_blank() +
geom_rect(aes(xmin=1, xmax=2,
ymin=1, ymax=2)) +
coord_fixed(clip="off") #a plain old nice grey rectangle
my_arrow = linesGrob(arrow=arrow(type="open", ends="first", length=unit(4,"mm")))
x + annotation_custom(my_arrow, xmin=1.5,xmax=2.2, ymin=1.5,ymax=1.25) #South-West :-)
x + annotation_custom(my_arrow, xmin=1.5,xmax=2.2, ymin=1.25,ymax=1.5) #Also South-West :-(
如何构造这样的箭头?
annotation_custom
似乎与从矩形或图像中获得的最小和最大坐标相关联。为了使箭头有意义,它需要一些东西来解释为方向。我正在切换到 annotate
使用分段几何,并保存箭头以供重用。
my_arrow <- arrow(type = "open", ends = "first", length = unit(4, "mm"))
x +
annotate("segment", x = 1.5, xend = 2.2, y = 1.5, yend = 1.25, arrow = my_arrow) +
annotate("segment", x = 1.5, xend = 2.2, y = 1.25, yend = 1.5, arrow = my_arrow)
由于 annotate
没有 data
参数,您不能 (AFAIK) 使用 aes
映射数据框变量,但您可以给它向量以收紧一次通话。
x +
annotate("segment", x = 1.5, xend = 2.2, y = c(1.5, 1.25), yend = c(1.25, 1.5), arrow = my_arrow)
# same output
编辑添加: 根据评论,将线段坐标放在数据框中可能有意义,这样您也可以参考它们来放置标签。
coords <- tibble::tribble(
~x, ~xend, ~y, ~yend, ~lbl,
1.5, 2.2, 1.5, 1.25, "Still a square",
1.5, 2.2, 1.25, 1.5, "This is a square"
)
x +
annotate("segment", x = coords$x, xend = coords$xend, y = coords$y, yend = coords$yend, arrow = my_arrow) +
geom_text(aes(label = lbl, x = xend, y = yend), data = coords, hjust = 0)