Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R Plotting - Function Curve Plots

R Plotting - Function Curve Plots

Function curve plots are an important tool for studying functions.

The curve() function in R can plot the graph of a function, with the code format as follows:

curve(expr, from = NULL, to = NULL, n = 101, add = FALSE,

      type = "l", xname = "x", xlab = xname, ylab = NULL,

      log = NULL, xlim = NULL, …)



# S3 function methods

plot(x, y = 0, to = 1, from = y, xlim = NULL, ylab = NULL, …)

**Note:** R has S3 and S4 classes. S3 classes are more widely used, simple and rough to create but flexible, while S4 classes are more refined.

Parameters:

In the plot function, x and y represent the horizontal and vertical coordinates of the plotted figure, respectively.

Below we plot a graph of the sin(x) function:

curve(sin(x), -2 * pi, 2 * pi)

Note: Any computer plotting tool draws a schematic diagram; it cannot guarantee an exact match with the real function graph. It simply takes a point at regular intervals, computes the "height" of that point, and plots it. To keep the curve continuous, adjacent points are connected by straight lines, so in some cases, such as tan(x), errors may occur:

A breakpoint appears at every position of (2n+1)Pi / 2, but R's graph connects them. Please keep this in mind.

Of course, not all functions support vectorized operations like sin does. We can also manually generate a sequence of numbers and then use the plot function to generate the function graph. Suppose the function f only accepts a single value as its argument:

Example

Define the function f

f

=

function

(

x

)

{

   

if

(

x

=

0

)

{

        x

   

}

else

{

        x

^

2

   

}

}

Generate the independent variable sequence

x

=

seq

(

2

,

2

,

length

=

100

)

Generate the dependent variable sequence

y

=

rep

(

0

,

length

(

x

)

)

j

=

1

for

(

i

in

x

)

{

    y

[

j

]

=

f

(

i

)

    j

=

j

1

}

Plot the graph

plot

(

x, y, type

=

'l'

)

Next, we use the plot() function to plot vector data:

Example

Vector data

v

<-

c

(

7

,

12

,

28

,

3

,

41

)

Generate the image

png

(

file

=

"line_chart_label_colored.jpg"

)

Plot with the line color set to red; the main parameter is used to set the title

plot

(

v,type

=

"o"

,

col

=

"red"

, xlab

=

"Month"

, ylab

=

"Rain fall"

,

   main

=

"Rain fall chart"

)