在R中绘制两个函数的两条不同曲线时出错

时间:2017-10-30 07:49:03

标签: r

a<-function(x) exp(-x) b<-function(x) 0.75*exp(-0.75*x) plot(a,xlim=c(-3,3),type="l",col="red3",lwd=2) lines(b,xlim=c(-3,3),type="l",col="blue3")

我想在一个轴上绘制这两个函数的图形,但错误显示: as.double(x)出错:   不能强制类型'封闭'强加到'double'类型的向量

如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

这是一种利用函数曲线的方法,该曲线在fromto定义的区间内绘制对应于函数的曲线。

a <- function(x) exp(-x)
b <- function(x) 0.75*exp(-0.75*x)
plot(a, xlim = c(-3, 3), type = "l",col = "red3", lwd = 2)
curve(b, from = -3, to = 3, col = "blue3", add = T, lwd = 2)
legend("topright", c("a", "b"), col = c("red3", "blue3"), lty = 1, lwd = 2)

enter image description here

plot的调用实际上是对plot.function调用类function的S3方法,因为第一个参数是一个函数。如果文档调用?plot.function,则curve {graphics}类型为curve(a, from = -3, to = 3, col = "red3", lwd = 2) curve(b, from = -3, to = 3, col = "blue3", add = T, lwd = 2) legend("topright", c("a", "b"), col = c("red3", "blue3"), lty = 1, lwd = 2)

等效方法是:

plot(a, xlim = c(-3, 3), type = "l",col = "red3", lwd = 2)
plot(b, xlim = c(-3, 3), type = "l",col = "blue3", lwd = 2, add = T)
legend("topright", c("a", "b"), col = c("red3", "blue3"), lty = 1, lwd = 2)

curve

因为他们都致电protect_from_forgery with: :exception

答案 1 :(得分:0)

a<-function(x) exp(-x)
b<-function(x) 0.75*exp(-0.75*x)

plot(a,xlim=c(-3,3),type="l",col="red3",lwd=2)
plot(b,xlim=c(-3,3),type="l",col="blue3", add = TRUE)

使用plot()代替lines()并添加add = TRUE参数

enter image description here

编辑:但我建议使用ggplot进行图形处理。这段代码:

library(ggplot2)

ggplot(data.frame(x=c(-3,3)), aes(x)) +
  stat_function(fun=a, geom="line", aes(colour="Function a: exp(-x)")) +
  stat_function(fun=b, geom="line", aes(colour="Function b: 0.75*exp(-0.75*x)")) +
  labs(colour = "Functions")

会给你这个漂亮的形象:

enter image description here