The “geom_smooth” Function in R

  • Package: ggplot2

  • Purpose: To add a smooth curve to a scatter plot for visualizing trends.

  • General Class: Geometric object for adding a smoothed conditional mean.

  • Required Argument(s):

    • mapping: Aesthetic mappings.

  • Notable Optional Arguments:

    • data: The data to be displayed in this layer.

    • method: Smoothing method (e.g., “loess” or “lm”).

    • formula: Formula to use in the smoothing method.

    • se: Should a confidence interval be drawn around the smooth?

    • level: Confidence level of the interval.

    • method.args: Additional arguments for the smoothing method.

    • n: Number of points to evaluate smooth.

    • span: Controls the amount of smoothing.

    • degree: The degree of the polynomial for polynomial smoothing.

    • family: The family of the generalized additive model (GAM).

  • Example:

  • # Example usage
    library(ggplot2)

    # Create two variables x and y
    x = rnorm(100)
    y = rnorm(100) + 2 * x

    # Create a data frame
    my_data <- data.frame(x, y)

    # Create a ggplot object with a scatter plot and smoothed curve using geom_smooth
    my_plot <- ggplot(data = my_data, aes(x = x, y = y)) +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE, color = "blue") +
    labs(title = "Scatter Plot with Smoothed Curve", x = "X-axis", y = "Y-axis")

    # Print the plot
    print(my_plot)

  • In this example, the geom_smooth function from the ggplot2 package is used to add a linear regression line to a scatter plot. The method argument specifies the smoothing method, and se controls whether to include a confidence interval around the smooth.

Previous
Previous

The “geom_violin” Function in R

Next
Next

The “geom_histogram” Function in R