如何在R中绘制函数曲线

时间:2014-09-29 01:20:05

标签: r plot ggplot2 lattice

这样的函数绘制简单曲线有哪些替代方法
eq = function(x){x*x}

在R?

这听起来是一个显而易见的问题,但我只能在stackoverflow上找到这些相关问题,但它们都更具体

我希望我没有写一个重复的问题。

6 个答案:

答案 0 :(得分:62)

我在网上做了一些搜索,这是我找到的一些方法:

最简单的方法是使用没有预定义函数的曲线

curve(x^2, from=1, to=50, , xlab="x", ylab="y")

enter image description here

您还可以在具有预定义功能时使用曲线

eq = function(x){x*x}
curve(eq, from=1, to=50, xlab="x", ylab="y")

enter image description here

如果你想使用ggplot,你可以在qplot

之间进行选择
library("ggplot2")
eq = function(x){x*x}
qplot(c(1,50), fun=eq, stat="function", geom="line", xlab="x", ylab="y")

enter image description here

和ggplot

library("ggplot2")
eq = function(x){x*x}
ggplot(data.frame(x=c(1, 50)), aes(x=x)) + stat_function(fun=eq, geom="line") + xlab("x") + ylab("y")

enter image description here

答案 1 :(得分:26)

plot有一个plot.function方法

plot(eq, 1, 1000)

或者

curve(eq, 1, 1000)

答案 2 :(得分:22)

你的意思是这样吗?

> eq = function(x){x*x}
> plot(eq(1:1000), type='l')

Plot of eq over range 1:1000

(或任何与您的功能相关的值范围)

答案 3 :(得分:1)

这是格子版本:

library(lattice)
eq<-function(x) {x*x}
X<-1:1000
xyplot(eq(X)~X,type="l")

Lattice output

答案 4 :(得分:1)

我需要其他设置的格子解决方案:

library(lattice)
distribution<-function(x) {2^(-x*2)}
X<-seq(0,10,0.00001)
xyplot(distribution(X)~X,type="l", col = rgb(red = 255, green = 90, blue = 0, maxColorValue = 255), cex.lab = 3.5, cex.axis = 3.5, lwd=2 )
  1. 如果您需要x的值范围以不同于1的增量绘制,例如0.00001你可以使用:
  2.   

    X&LT; -SEQ(0,10,0.00001)

    1. 您可以通过定义rgb值来更改线条的颜色:
    2.   

      col = rgb(红色= 255,绿色= 90,蓝色= 0,maxColorValue = 255)

      1. 您可以通过设置:
      2. 更改绘制线条的宽度
          

        lwd = 2

        1. 您可以通过缩放来更改标签的大小:
        2.   

          cex.lab = 3.5,cex.axis = 3.5

          Example plot

答案 5 :(得分:0)

就像sjdh也提到的那样,ggplot2可以解救。不创建虚拟数据集的一种更直观的方法是使用xlim:

library(ggplot2)
eq <- function(x){sin(x)}
base <- ggplot() + xlim(0, 30)
base + geom_function(fun=eq)

另外,对于更平滑的图形,我们可以使用n设置图形被插值的点数:

base + geom_function(fun=eq, n=10000)