gpt4 book ai didi

R:将 "vline"和 "hline"语句组合在一起(ggplot2)

转载 作者:行者123 更新时间:2023-12-03 08:17:55 24 4
gpt4 key购买 nike

我正在使用 R 编程语言。最近,我学习了如何使用 ggplot 库“绘制”水平线和垂直线:

library(ggplot2)

# Simple scatter plot
sp <- ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point()

# Add horizontal line at y = 2O

a = sp + geom_hline(yintercept=20)

b = sp + geom_vline(xintercept = 3)

enter image description here

现在,我尝试将这些陈述组合在一起 - 例如:

c = sp + geom_hline(yintercept=20) +  geom_hline(yintercept=15) + geom_vline(xintercept = 3) +
geom_vline(xintercept = 5) + geom_vline(xintercept = 6) + geom_hline(yintercept=35)

enter image description here

问题:我正在尝试修改上面的图,使其看起来像这样:

enter image description here

有人可以告诉我该怎么做吗?或者您是否必须手动将此图导出到 Microsoft Paint 中并在那里进行更改?

谢谢

最佳答案

您可以使用annotate添加图层。每个段都是下面四个向量的匹配元素。即第一段从 (-Inf,15) 开始,到 (3,15) 结束。

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
annotate("segment",
x = c(-Inf, 3, -Inf, 5, -Inf, 6),
y = c(15, 15, 20, 20, 35, 35),
xend = c(3, 3, 5, 5, 6, 6),
yend = c(15, -Inf, 20, -Inf, 35, -Inf))

enter image description here

或者也许定义一个函数,从一个点向轴绘制两条线(假设这里的点是正数,所以它应该朝向 -Inf)会更容易。要使函数输出多个 ggplot2 元素,请将它们放入列表中:

draw_guides<- function(x, y) {
list(geom_segment(aes(x = -Inf, xend = x, y = y, yend = y)),
geom_segment(aes(x = x, xend = x, y = y, yend = -Inf)))
}

然后您可以调用每一个来更轻松地重新创建所需的图形:

ggplot(data=mtcars, aes(x=wt, y=mpg)) + geom_point() +
draw_guides(3,15) +
draw_guides(5,20) +
draw_guides(6,35)

关于R:将 "vline"和 "hline"语句组合在一起(ggplot2),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68788647/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com