我使用R和ggplot2包在一个图上绘制几个数学函数。这是一个最小的工作示例,绘制-5中的两个简单方程式。 x< 5间隔。
library(ggplot2)
### define math functions
line1 <- function(x) {
x^2
}
line2 <- function(x) {
x^3
}
### build plot
f1 =
#make basic plot
ggplot(data.frame(x=c(-5,5)), aes(x)) +
# draw line 1
stat_function(fun=line1, geom="line", colour="red") +
# draw line 2
stat_function(fun=line2, geom="line", colour="blue") +
print(f1)
到目前为止一直很好:两条线都是绘制的。现在是我的问题。我想在x值的特定间隔中绘制每个方程。 (例如,对于x <0,第1行,对于x> 0,第2行)。我不知道该怎么做。
我尝试在每个stat_funcion()中设置不同的xlimits,但它不起作用。可能无法在stat_function()中定义任何xlim。
或者,我在定义函数时尝试包含if语句,但它也不起作用。 (可能它甚至不是最好的approch ..)
### define math functions
line1 <- function(x) {
if (x < 0) {
x^2 } else {
}
}
line2 <- function(x) {
if (x > 0) {
x^3 } else {
}
}
### build plot
f1 =
#make basic plot
ggplot(data.frame(x=c(-5,5)), aes(x)) +
# draw line 1
stat_function(fun=line1, geom="line", colour="red") +
# draw line 2
stat_function(fun=line2, geom="line", colour="blue") +
print(f1)
我非常感谢任何建议。
答案 0 :(得分:2)
编写一个装饰函数,如果超出给定范围,则返回NA:
rwrap=function(f,xmin,xmax){ff=function(x){y=f(x);y[x>xmax]=NA;y[x<xmin]=NA;y}}
现在有一些数据和一个例子:
d=data.frame(x=c(-5,5))
ggplot(d,aes(x=x))+stat_function(fun=rwrap(line1,0,5),geom="line",col="blue") + stat_function(fun=rwrap(line2,-5,0),geom="line",col="red")
如果您还没有看到这样的装饰功能,那么请稍微解释一下。它基本上将你的函数包装在一些代码中,返回一个类似的函数。
> line1(-5:5)
[1] 25 16 9 4 1 0 1 4 9 16 25
> rwrap(line1,0,3)(-5:5)
[1] NA NA NA NA NA 0 1 4 9 NA NA
如果需要,您可以保存包装的功能:
> w2 = rwrap(line2,0,3)
> w2(-5:5)
[1] NA NA NA NA NA 0 1 8 27 NA NA
在上面的例子中,我刚刚完成了一切。