Visualizing Data in R with Default Package:
Curve and RColorBrewer

Asst. Prof. Dr. Somsak Chanaim

International College of Digital Innovation, CMU

June 23, 2026

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

Complete the script to evaluate a quadratic mathematical function over a specified interval and assign the proper axis labels.

Target output

Complete the code

(x^2, = -10, = 10,
xlab = "x values",
ylab = "y values",
main = "Plot of y = x^2")

Exercise 2: Superimposing Multiple Functional Curves

Complete the script to plot an initial cubic function and layer a secondary function over the same graphical space using a customized palette.

Target output

Complete the code

curve(x^3, from = -2, to = 2, = "blue", main = "Multiple Curves")
curve(x^2, from = -2, to = 2, col = "red", = TRUE)

Exercise 3: Plotting a Custom Damped Function

Complete the script to evaluate a composite mathematical function over a specified interval, applying a dashed line style and custom colors.

Target output

Complete the code

curve((x) * (-0.1 * x), from = 0, to = 20,
col = "blue",
= 2,
ylab = "f(x)",
main = "Plot of f(x) = sin(x) * exp(-0.1x)")

Exercise 4: Logarithmic Domain Interval Exploration

Complete the script to evaluate a logarithmic function across expanding intervals, layer the subsequent curves, and position an explanatory legend.

Target output

Complete the code

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

Exercise 5: Advanced Graphical Layer Annotations

Complete the script to map a continuous square root curve, superimpose discrete coordinate points, and append spatial text annotations.

Target output

Complete the code

(sqrt(x), from = 0, to = 25,
col = "purple",
ylab = "sqrt(x)",
main = "Plot of y = sqrt(x) with points and annotations")

(c(5, 10, 15, 20), sqrt(c(5, 10, 15, 20)),
pch = 19,
col = "red")

(c(5, 10, 15, 20), sqrt(c(5, 10, 15, 20)) + 0.5,
= c("(5, sqrt(5))", "(10, sqrt(10))", "(15, sqrt(15))", "(20, sqrt(20))"),
pos = 3)

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

Why Colorblind-Safe Palettes Matter

  • Around 8% of men and 0.5% of women have some form of color vision deficiency

  • Default color schemes may be indistinguishable for many viewers

  • In data visualization, color confusion = information loss

  • Colorblind-safe palettes help ensure:

    • Accessibility

    • Clarity

    • Reproducibility

The Okabe–Ito palette is one of the most widely recommended colorblind-safe palettes.

The Okabe–Ito Palette

  • Proposed by Masataka Okabe and Kei Ito (2008)

  • Designed so that colors remain distinguishable:

    • For most types of color vision deficiency

    • When printed in grayscale

    • On projectors and screens

Hex values:

  • Black: #000000
  • Orange: #E69F00
  • Sky Blue: #56B4E9
  • Bluish Green: #009E73
  • Yellow: #F0E442
  • Blue: #0072B2
  • Vermillion: #D55E00
  • Reddish Purple: #CC79A7

Okabe–Ito Palette in R (Vector)

okabe_ito <- c(
  black   = "#000000", orange  = "#E69F00",
  skyblue = "#56B4E9", green   = "#009E73",
  yellow  = "#F0E442", blue    = "#0072B2",
  vermil  = "#D55E00", purple  = "#CC79A7"
)
okabe_ito
    black    orange   skyblue     green    yellow      blue    vermil    purple 
"#000000" "#E69F00" "#56B4E9" "#009E73" "#F0E442" "#0072B2" "#D55E00" "#CC79A7" 
  • Store the palette as a named character vector
  • Use it consistently in base R plots and ggplot2
  • Names are optional but helpful for readability

Visualizing the Palette in Base R

  • Each bar represents one color from the palette
  • Use this as a quick sanity check in your own environment
  • Good slide to show your audience the actual colors

Using Okabe–Ito in Base R Plots

  • Use colors via okabe_ito["name"] for readability
  • Combine with different pch shapes for extra distinguishability

Using Okabe–Ito in ggplot2 (Manual Scales)

  • scale_color_okabe_ito() from library(ggokabeito) is the simplest way to apply the palette
  • Choose a subset of colors based on the number of groups
  • Keep the mapping consistent across figures

Good Practices When Using Okabe–Ito in R

  • Use no more than 6–8 colors in a single plot if possible

  • Combine color with:

    • Shape (pch)
    • Line type (linetype)
    • Faceting (facet_wrap, facet_grid)
  • Keep color assignments consistent across plots:

    • e.g., Group A is always blue
  • Document the palette and mapping in your code:

    • Improves reproducibility
    • Makes collaboration easier

In Summary

  • Okabe–Ito is a colorblind-safe, publication-ready palette

  • Easy to implement in R as:

    • A simple vector
    • A palette function
    • Manual color / fill scales in ggplot2
  • Great for:

    • Line plots
    • Bar plots
    • Scatter plots
    • Multi-panel figures

Adopting accessible color choices is a small change with a big impact.