R语言 如何使vline和hline在ggplot中的某个点停止

lyr7nygr  于 2023-04-09  发布在  其他
关注(0)|答案(1)|浏览(141)
# load ggplot2 library
library(ggplot2)

# create example data
x <- rnorm(50)
y <- x + rnorm(50)

# create ggplot object with equal axis lengths
p <- ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point() + geom_abline()
p <- p + scale_y_continuous(breaks = seq(-3,3, by=1),limits = c(-3,3))
p <- p + scale_x_continuous(breaks = seq(-3,3, by=1),limits = c(-3,3))

# add vertical and horizontal lines
p <- p + geom_vline(xintercept = -1, color = "blue") +
  geom_hline(yintercept = -1, color = "blue")

我希望线在任何一个轴上都不高于-1,但似乎不知道如何做到这一点。任何帮助都表示感谢

h6my8fg2

h6my8fg21#

您可以使用两个geom_segment来指定正确的x和y坐标,如下所示:

# load ggplot2 library
library(ggplot2)

# create example data
x <- rnorm(50)
y <- x + rnorm(50)

# create ggplot object with equal axis lengths
p <- ggplot(data = data.frame(x, y), aes(x = x, y = y)) +
  geom_point() + geom_abline()
p <- p + scale_y_continuous(breaks = seq(-3,3, by=1),limits = c(-3,3))
p <- p + scale_x_continuous(breaks = seq(-3,3, by=1),limits = c(-3,3))

# add vertical and horizontal lines
p + geom_segment(x = -Inf, xend = -1, y = -1, yend = -1, color = "blue") +
  geom_segment(x = -1, xend = -1, y = -Inf, yend = -1, color = "blue")

创建于2023-04-08使用reprex v2.0.2

相关问题