将箭头绘制在图形外部而不是内部

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

我正在尝试将箭头绘制在图之外。我尝试了许多不同的选项,但他们不断在图中绘制箭头。有没有办法将其绘制在边界框之外?

set.seed(57)
discharge <- data.frame(date = seq(as.Date("2011-01-01"), as.Date("2011-12-31"), by="days"),
discharge = rexp(365))

test <- ggplot(discharge) +
geom_line(aes(x = date, y = discharge)) +
geom_hline(yintercept = 5.5, linetype= "dashed", color = "red") + 
geom_text(aes(x = date[13], y = 5.5, label = "High"))

(test + annotate(geom = "segment", x = as.Date("2011-01-01"), 
              y = -1, xend = as.Date("2011-01-01"), yend = 0, 
              arrow = arrow(length = unit(3, "mm")), color = "red"))
r annotate geom-segment
1个回答
0
投票

ggplot2 >= 3.5.0
(!!!)引入的一个很好的功能是,现在可以在绘图面板的相对单位中放置注释(参见here)。为此,我们必须将
annotate
内的位置包裹在
I()
中。此外,我们必须像往常一样在
clip="off"
中设置
coord_cartesian
并在绘图面板之外留出一些空间,例如通过
plot.margin

set.seed(57)
discharge <- data.frame(
  date = seq(as.Date("2011-01-01"), as.Date("2011-12-31"), by = "days"),
  discharge = rexp(365)
)

library(ggplot2)

packageVersion("ggplot2")
#> [1] '3.5.0'

test <- ggplot(discharge) +
  geom_line(aes(x = date, y = discharge)) +
  geom_hline(yintercept = 5.5, linetype = "dashed", color = "red") +
  geom_text(data = ~.x[13, , drop = FALSE], aes(x = date, y = 5.5, label = "High"))

test + 
  annotate(
    geom = "segment", x = as.Date("2011-01-01"),
    y = I(-.125), xend = as.Date("2011-01-01"), yend = I(-.05),
    arrow = arrow(length = unit(3, "mm")), color = "red"
  ) +
  coord_cartesian(clip = "off") +
  theme(plot.margin = margin(5.5, 5.5, 22, 5.5))

© www.soinside.com 2019 - 2024. All rights reserved.