gpt4 book ai didi

r - 在不连接 "jump"的情况下在 R 中绘制不连续函数

转载 作者:行者123 更新时间:2023-12-01 22:53:54 25 4
gpt4 key购买 nike

我想在不连接跳转的情况下绘制一个不连续的函数。例如,在下图中,我想删除连接 (0.5, 0.5) 和 (0.5, 1.5) 的线。

f <- function(x){
(x < .5) * (x) + (x >= .5) * (x + 1)
}
ggplot()+
geom_function(fun = f)

编辑:我正在寻找一种解决方案,即使折扣点不是整数,例如 pi/10,也能正常工作。

最佳答案

您可以编写一个小的包装函数来查找给定函数中的不连续点并将它们绘制为单独的组:

plot_fun <- function(fun, from = 0, to = 1, by = 0.001) {

x <- seq(from, to, by)
groups <- cut(x, c(-Inf, x[which(abs(diff(fun(x))) > 0.1)], Inf))
df <- data.frame(x, groups, y = fun(x))

ggplot(df, aes(x, y, group = groups)) +
geom_line()
}

这允许

plot_fun(f)

enter image description here

plot_fun(floor, 0, 10)

enter image description here

关于r - 在不连接 "jump"的情况下在 R 中绘制不连续函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73695544/

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