Visualizing Data in R with Default Package:
Curve and RColorBrewer

Somsak Chanaim

International College of Digital Innovation, CMU

October 30, 2024

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.

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].

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.

The lty can be used to control the style of lines in plots, such as solid, dashed, dotted, etc.

Here are 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.

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