Easy Tutorial
❮ R Scatterplots Charts R Setup ❯

R Plotting - Function Curve Graph

In R, the curve() function can be used to plot the graph of a function. The code format is 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 method for functions
plot(x, y = 0, to = 1, from = y, xlim = NULL, ylab = NULL, …)

Note: R has S3 and S4 classes. S3 classes are widely used, simple to create, and flexible, while S4 classes are more sophisticated.

Parameters:

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

Below is an example of plotting a sin(x) function:

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

Note: Any computer-generated plot is a schematic diagram and may not perfectly match the true function graph. It samples points at intervals, calculates their "heights," and connects adjacent points with lines to maintain continuity. In some cases, such as tan(x), this can lead to errors:

At each ((2n+1)\pi / 2) position, there will be a break, but R connects these points. Please understand this.

Not all functions support vector processing like sin. We can also manually generate a sequence of numbers and use the plot function to create a function graph. Suppose function f only supports a single value as a parameter:

Example

# Define function f
f = function (x) {
    if (x >= 0) {
        x
    } else {
        x ^ 2
    }
}

# Generate sequence of independent variables
x = seq(-2, 2, length=100)

# Generate sequence of dependent variables
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 image
png(file = "line_chart_label_colored.jpg")

# Plot, with line color red and main parameter for title
plot(v,type = "o", col = "red", xlab = "Month", ylab = "Rain fall",
   main = "Rain fall chart")
❮ R Scatterplots Charts R Setup ❯