Visualizing Data in R with Default Package:
Curve and RColorBrewer

Somsak Chanaim

International College of Digital Innovation, CMU

October 29, 2025

My Shiny App

View slides in full screen

Interactive Example

Draw in Curve in R

The curve() function in R is used to plot mathematical functions over a specified interval.

It’s particularly useful for visualizing the shape of a function or for adding function curves to existing plots.

The curve() function is a powerful tool for visualizing mathematical expressions and functions directly in R.

Built-in mathematical functions

R has hundreds of built-in mathematical functions, and most of them come from its base and stats packages (which load automatically).

1. Basic Arithmetic

Function Example Meaning
+ - * / 5 + 2, 8 / 4 Addition, subtraction, multiplication, division
^ or ** 3^2 Power
%% 5 %% 2 Modulus (remainder)
%/% 5 %/% 2 Integer division

2. Rounding and Integer Functions

Function Example Description
round(x, n) round(3.14159, 2) → 3.14 Round to n digits
ceiling(x) ceiling(3.2) → 4 Round up
floor(x) floor(3.8) → 3 Round down
trunc(x) trunc(-3.9) → -3 Truncate decimals
signif(x, n) signif(1234, 2) → 1200 Round to significant digits
abs(x) abs(-5) → 5 Absolute value
sign(x) sign(-10) → -1 Sign of number

3. Exponential and Logarithmic

Function Example Description
exp(x) exp(1)e Exponential function
log(x) log(10) → ln(10) Natural log (base e)
log10(x) log10(100) → 2 Log base 10
log2(x) log2(8) → 3 Log base 2

4. Trigonometric Functions

Function Example Description
sin(x), cos(x), tan(x) sin(pi/2) → 1 Trig functions (radians)
asin(x), acos(x), atan(x) atan(1) → π/4 Inverse trig
sinh(x), cosh(x), tanh(x) Hyperbolic functions
asinh(x), acosh(x), atanh(x) Inverse hyperbolic

5. Statistical & Aggregation

Function Example Description
sum(x) sum(1:5) → 15 Sum
mean(x) mean(c(2,4,6)) → 4 Arithmetic mean
median(x) median(c(1,9,3)) → 3 Median
var(x), sd(x) sd(1:5) → 1.58 Variance / SD
min(x), max(x) Minimum / Maximum
range(x) Range (min & max)
quantile(x, p) quantile(x, 0.25) Quantiles
sum(is.na(x)) Count missing values

6. Complex Numbers

Function Example Description
complex(real, imaginary) complex(real=2, imaginary=3) Create complex number
Re(z) / Im(z) Extract real / imaginary parts
Mod(z) Magnitude
Arg(z) Argument (angle)
Conj(z) Conjugate

7. Sequences and Random Numbers

Function Example Description
seq(from, to, by) seq(1,10,2) Sequence
rep(x, times) rep(1:3, 2) Repeat
runif(n, min, max) runif(5, 0, 1) Uniform random numbers
rnorm(n, mean, sd) rnorm(5, 0, 1) Normal random numbers
sample(x, size) sample(1:10, 3) Random sample

8. Matrix and Linear Algebra

Function Example Description
matrix(data, nrow, ncol) Create matrix
t(A) Transpose
%*% Matrix multiplication
solve(A, b) Solve linear system
det(A) Determinant
eigen(A) Eigenvalues & vectors
diag(x) Diagonal matrix
rowSums(A), colSums(A) Sum by row/column

9. Special Mathematical Functions

Function Example Description
factorial(n) factorial(5) → 120 Factorial
choose(n, k) choose(5,2) → 10 Binomial coefficient
gamma(x) / lgamma(x) Gamma function / log(Γ(x))
digamma(x) / trigamma(x) Derivatives of Γ(x)
beta(a,b) Beta function

10. Useful Constants

Constant Meaning
pi π = 3.14159…
Inf, -Inf Infinity
NA Missing value
NaN Not a number
.Machine$double.eps Machine precision (~2.22e-16)

Basic Syntax

curve(expr, from = , to = , add = FALSE, col = )

Parameters:

  • expr: The mathematical expression to plot. This can be a function or an expression in terms of x.

  • from: The starting value of x for which the function will be plotted.

  • to: The ending value of x for which the function will be plotted.

  • add: If TRUE, the curve will be added to an existing plot. If FALSE (default), a new plot will be created.

  • col: The color of the curve.

Example 1: Plotting a Simple Function

Let’s plot the function \(y = x^2\) over the interval [-10, 10].

Note: If we want to hide the box around the graph, we can set the argument bty = "n".

Example 2: Adding a Curve to an Existing Plot

You can add a curve to an existing plot by setting

add = TRUE.

  • The lwd argument controls the thickness of lines in plots.

  • A larger lwd value increases the line thickness, while a smaller value decreases it.

  • You can use lwd in any function that involves drawing lines, such as plot(), curve(), lines(), and abline().

Example 3: Plotting a Custom Function

You can also plot a custom function using the curve() function.

In R, the lty argument is used in plotting functions to specify the line type, such as solid, dashed, or dotted.

The common values for lty:

  • 0: Blank (no line)

  • 1: Solid line (default)

  • 2: Dashed line

  • 3: Dotted line

  • 4: Dot-dash line

  • 5: Long-dash line

  • 6: Two-dash line

Question

From the example above change the lty from 1 to another number.

Draw the curve from 10 functions

1. Linear Function:

\[ y = 2x + 1 ,~ x\in[-5,5] \]

2. Quadratic Function:

\[ y = x^2 - 4x + 3,~ x\in[-5,10] \]

3. Cubic Function:

\[ y = x^3 - 3x^2 + 2,~ x\in[-5,5] \]

4. Exponential Function:

\[ y = e^{-0.5x} ,~ x\in[-5,5] \]

5. Logarithmic Function:

\[ y = \log(x) ,~ x\in[0.001,10] \]

6. Sine Function:

\[ y = \sin(x),~ x\in[-4\pi,4\pi] \]

7. Cosine Function:

\[ y = \cos(x) ~ x\in[-4\pi,4\pi] \]

8. Tangent Function:

\[ y = \tan(x), ~ x\in[-4\pi,4\pi] \]

9. Reciprocal Function:

\[ y = \frac{1}{x}, ~ x\in[0.0001,2] \]

10. Gaussian (Normal) Distribution:

\[y = \frac{1}{\sqrt{2\pi}} e^{-\frac{x^2}{2}},~ x\in[-4,4]\]

Add the legend in the curve plot

Sine function:

\[ y = \sin(x),~ x\in[-4\pi,4\pi] \]

Cosine function:

\[ y = \cos(x) ~ x\in[-4\pi,4\pi] \]

Exercise 1: Basic Curve Plotting

Solution:

# Plot y = x^2 over the interval [-10, 10]
curve(x^2, from = -10, to = 10, 
      xlab = "x values", 
      ylab = "y values", 
      main = "Plot of y = x^2")

Objective: Plot a simple mathematical function.

  • Use the curve() function to plot the function \(y = x^2\) over the interval \([-10, 10]\).

  • Label the x-axis as “x values” and the y-axis as “y values”.

  • Add a main title to the plot that says “Plot of y = x^2”.

Exercise 2: Adding Multiple Curves

Solution:

# Plot y = x^2 and y = x^3 on the same graph
curve(x^2, from = -5, to = 5, 
      col = "blue", 
      lty = 1, 
      ylab = "y values", 
      main = "Plot of y = x^2 and y = x^3")
curve(x^3, from = -5, to = 5, 
      col = "red", 
      lty = 2, 
      add = TRUE)

# Add a legend
legend("topleft", legend = c("y = x^2", "y = x^3"), 
       col = c("blue", "red"), 
       lty = 1:2)

Objective: Overlay multiple curves on the same plot.

  • Use the curve() function to plot \(y = x^2\) and \(y = x^3\) on the same graph over the interval \([-5, 5]\).

  • Use different colors and line types for each curve.

  • Add a legend to distinguish between the two curves.

Exercise 3: Plotting a Custom Function

Solution:


# Plot the custom function over the interval [0, 20]
curve(sin(x) * exp(-0.1 * x), from = 0, to = 20, 
      col = "blue", 
      lty = 2, 
      ylab = "f(x)", 
      main = "Plot of f(x) = sin(x) * exp(-0.1x)")

Objective: Create and plot a custom function.

  • Define a custom function in R, say \(f(x) = \sin(x) \times \exp(-0.1x)\).

  • Use the curve() function to plot this custom function over the interval \([0, 20]\).

  • Use a dashed line type and a blue color for the plot.

Exercise 4: Exploring Different Intervals

Solution:

# Plot y = log(x) over different intervals
curve(log(x), from = 0.1, to = 10, 
      col = "blue", 
      ylab = "log(x)", 
      main = "Plot of y = log(x) over different intervals")
curve(log(x), from = 1, to = 100, 
      col = "red", 
      add = TRUE)
curve(log(x), from = 10, to = 1000, 
      col = "green", 
      add = TRUE)

# Add a legend
legend("topleft", legend = c("[0.1, 10]", "[1, 100]", "[10, 1000]"), 
       col = c("blue", "red", "green"), 
       lty = 1)

Objective: Understand the impact of different intervals.

  • Plot the function \(y = \log(x)\) using the curve() function over three different intervals: \([0.1, 10]\), \([1, 100]\), and \([10, 1000]\).

  • Plot all three curves on the same graph using different colors.

  • Add a legend to explain which color corresponds to which interval.

Exercise 5: Adding Points and Annotations

Solution:

# Plot y = sqrt(x) over the interval [0, 25]
curve(sqrt(x), from = 0, to = 25, 
      col = "purple", 
      ylab = "sqrt(x)", 
      main = "Plot of y = sqrt(x) with points and annotations")

# Add points at x = 5, 10, 15, 20
points(c(5, 10, 15, 20), sqrt(c(5, 10, 15, 20)), 
       pch = 19, 
       col = "red")

# Annotate each point with (x, y) values
text(c(5, 10, 15, 20), sqrt(c(5, 10, 15, 20)) + 0.5, 
     labels = c("(5, sqrt(5))", "(10, sqrt(10))", 
                "(15, sqrt(15))", "(20, sqrt(20))"), 
     pos = 3)

Objective: Enhance the plot with points (point() function) and annotations (text() function).

  • Use the curve() function to plot the function \(y = \sqrt{x}\) over the interval \([0, 25]\).

  • Add points at \(x = 5, 10, 15,\) and \(20\) on the curve.

  • Annotate each point with its corresponding \((x, y)\) value.

  • Add a title, and label the axes accordingly.

Interactive RColorBrewer

The package RColorBrewer

RColorBrewer is an R package that provides a set of color palettes for use in R graphics.

It is especially useful for creating visually appealing and colorblind-friendly plots.

The palettes in RColorBrewer are designed to be used with categorical, sequential, or diverging data.

Key Features of RColorBrewer:

Color Palettes: The package offers three types of color palettes:

  1. Sequential: These are suited for ordered data that progresses from low to high (e.g., Blues, Reds).

  2. Diverging: These are designed for data that diverges from a central point, with two contrasting colors on either end (e.g., RdBu, Spectral).

  3. Qualitative: These palettes are used for categorical data, where each category should be represented by a different color (e.g., Set1, Pastel2).

Colorblind-Friendly: Many of the palettes are designed to be colorblind-friendly, making your plots more accessible.

Installation

You can install RColorBrewer from CRAN using:

install.packages("RColorBrewer")

Usage

To use RColorBrewer, you first need to load the package and then explore the available palettes using functions like display.brewer.all() or brewer.pal().

Displaying All Palettes

This will show you all available color palettes in the package, organized by type (sequential, diverging, qualitative).

Using a Specific Palette

Functions in RColorBrewer:

  • brewer.pal(n, name): Generates a palette with n colors from the specified palette name.

  • display.brewer.all(): Displays all available palettes.

  • display.brewer.pal(n, name): Displays a specific palette with n colors.

  • colorRampPalette(colors): Creates a continuous color ramp from a palette.

  1. Blues

  2. BuGn (Blue-Green)

  3. BuPu (Blue-Purple)

  4. GnBu (Green-Blue)

  5. Greens

  6. Greys

  7. Oranges

  8. OrRd (Orange-Red)

  9. PuBu (Purple-Blue)

  10. PuBuGn (Purple-Blue-Green)

  11. PuRd (Purple-Red)

  12. Purples

  13. RdPu (Red-Purple)

  14. Reds

  15. YlGn (Yellow-Green)

  16. YlGnBu (Yellow-Green-Blue)

  17. YlOrBr (Yellow-Orange-Brown)

  18. YlOrRd (Yellow-Orange-Red)

These are used for data that diverges around a central value:

  1. BrBG (Brown-Blue-Green)

  2. PiYG (Pink-Yellow-Green)

  3. PRGn (Purple-Green)

  4. PuOr (Purple-Orange)

  5. RdBu (Red-Blue)

  6. RdGy (Red-Grey)

  7. RdYlBu (Red-Yellow-Blue)

  8. RdYlGn (Red-Yellow-Green)

  9. Spectral

These are used for categorical data where each category needs to be represented by a different color:

  1. Accent

  2. Dark2

  3. Paired

  4. Pastel1

  5. Pastel2

  6. Set1

  7. Set2

  8. Set3

Example of Color Palettes

  1. Blues

  2. BuGn (Blue-Green)

  3. BuPu (Blue-Purple)

  4. GnBu (Green-Blue)

  5. Greens

  6. Greys

  7. Oranges

  8. OrRd (Orange-Red)

  9. PuBu (Purple-Blue)

  10. PuBuGn (Purple-Blue-Green)

  11. PuRd (Purple-Red)

  12. Purples

  13. RdPu (Red-Purple)

  14. Reds

  15. YlGn (Yellow-Green)

  16. YlGnBu (Yellow-Green-Blue)

  17. YlOrBr (Yellow-Orange-Brown)

  18. YlOrRd (Yellow-Orange-Red)

These are used for data that diverges around a central value:

  1. BrBG (Brown-Blue-Green)

  2. PiYG (Pink-Yellow-Green)

  3. PRGn (Purple-Green)

  4. PuOr (Purple-Orange)

  5. RdBu (Red-Blue)

  6. RdGy (Red-Grey)

  7. RdYlBu (Red-Yellow-Blue)

  8. RdYlGn (Red-Yellow-Green)

  9. Spectral

These are used for categorical data where each category needs to be represented by a different color:

  1. Accent

  2. Dark2

  3. Paired

  4. Pastel1

  5. Pastel2

  6. Set1

  7. Set2

  8. Set3

Transparent color