【发布时间】: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 返回到您想要的范围之外。