【问题标题】:Plotting a function (having different equations for different range of x) in R在 R 中绘制一个函数(对于不同的 x 范围具有不同的方程)
【发布时间】:2014-03-28 01:35:26
【问题描述】:

我正在使用 R 和 ggplot2 包在一个绘图上绘制多个数学函数。这是一个最小的工作示例,在 -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 值的特定区间内绘制每个方程。 (例如,第 1 行表示 x 0)。我不知道该怎么做。

我尝试在每个 stat_funcion() 中设置不同的 xlimit,但它不起作用。可能无法在 stat_function() 中定义任何 xlim。

另外,我尝试在定义函数时包含 if 语句,但它也不起作用。 (而且可能它甚至不是最好的方法......)

### 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)

如果有任何建议,我将不胜感激。

【问题讨论】:

  • 向每个stat_function 添加一个具有不同x 范围的data 参数是不行的……我只能认为你必须在你想要的范围内评估你的函数进入数据框并将其传递给geom_line
  • 是的,我尝试了这种方法但没有成功。我不知道我的输入是否拼错了,或者这不是好方法。
  • 您还可以重写您的函数以将 NA 返回到您想要的范围之外。

标签: r ggplot2


【解决方案1】:

编写一个装饰函数,如果超出给定范围,则返回 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

在上面的例子中,我只是把所有的事情都做完了。

【讨论】:

  • 出色的解决方案:完美运行且非常干净!非常感谢!
  • 我想知道是否值得在这里向 Hadley W 询问 xrange 选项?
  • 为什么不呢。我认为这将是一个非常有用的选择。应该在ggplot2 google group 上发布功能请求还是有更好的地方?
  • 试试 ggplot2 github 存储库的 issue 部分。
猜你喜欢
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-10
  • 2021-10-17
  • 2019-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多