R courses

Adding a Polygon with the polygon() Function in R

Adding a Polygon with the polygon() Function Syntax of the polygon() Function The polygon() function draws a polygon defined by a series of points. Its basic syntax is:  polygon(x, y, border = NULL, col = NULL, lty = 1, lwd = 1) x: Numeric vector of x-coordinates for the vertices of the polygon. y: Numeric vector of y-coordinates for the vertices of the polygon. border: Color of the polygon border. (Default is NULL, meaning no border.) col: Color of the polygon fill. (Default is NULL, meaning no fill.) lty: Line type for the border. (Default is 1, solid line.) lwd: Line width of the border. (Default is 1.) Basic Example: Drawing a Simple Polygon Here’s how to create a basic polygon:  # Generate example data x <- c(2, 4, 6, 4) y <- c(2, 4, 2, 0) # Create a basic plot plot(1:10, 1:10, type = “n”, main = “Basic Polygon Example”) # Add a polygon polygon(x, y, border = “blue”, col = “lightblue”) x: x-coordinates of the polygon vertices. y: y-coordinates of the polygon vertices. border = “blue”: Border color of the polygon. col = “lightblue”: Fill color of the polygon. Creating a Complex Polygon You can draw polygons with more vertices for complex shapes. Example:  # Generate coordinates for a complex polygon x <- c(1, 3, 5, 7, 6, 4) y <- c(1, 2, 1, 4, 6, 4) # Create a basic plot plot(1:10, 1:10, type = “n”, main = “Complex Polygon”) # Add a complex polygon polygon(x, y, border = “red”, col = “yellow”) x and y: Coordinates for the vertices of the polygon. border = “red”: Border color of the polygon. col = “yellow”: Fill color of the polygon. Highlighting Areas Polygons can be used to highlight specific areas on the plot. Example:  # Generate example data x <- c(2, 4, 6, 4) y <- c(2, 4, 2, 0) # Create a basic plot plot(1:10, 1:10, type = “n”, main = “Highlighted Area”) # Add a polygon to highlight an area polygon(x, y, border = “blue”, col = rgb(0.5, 0.5, 1, 0.5)) rgb(0.5, 0.5, 1, 0.5): Defines a semi-transparent blue color for the polygon fill. Adding Polygons to Existing Plots You can add polygons to an existing plot using the polygon() function. Example:  # Generate example data x <- 1:10 y <- x^2 # Create a plot with the data plot(x, y, main = “Polygon on Existing Plot”) # Add a polygon polygon(c(3, 5, 7, 5), c(9, 25, 49, 16), border = “green”, col = “lightgreen”) c(3, 5, 7, 5): x-coordinates for the polygon vertices. c(9, 25, 49, 16): y-coordinates for the polygon vertices. Using Polygons for Area Plots Polygons can be used to create area plots or density plots. Example:  # Generate density data x <- seq(0, 10, length.out = 100) y1 <- dnorm(x, mean = 5, sd = 1) y2 <- dnorm(x, mean = 7, sd = 1.5) # Create a density plot plot(x, y1, type = “l”, col = “blue”, ylim = c(0, max(y1, y2)), main = “Area Plot”) # Add density areas with polygons polygon(c(x, rev(x)), c(y1, rep(0, length(x))), col = rgb(0.5, 0.5, 1, 0.5), border = NA) polygon(c(x, rev(x)), c(y2, rep(0, length(x))), col = rgb(1, 0.5, 0.5, 0.5), border = NA) c(x, rev(x)): x-coordinates for the polygon, doubled to close the shape. c(y1, rep(0, length(x))): y-coordinates for the polygon, with a line to 0 to close the shape. rgb(0.5, 0.5, 1, 0.5) and rgb(1, 0.5, 0.5, 0.5): Semi-transparent colors for the polygon fill. Summary polygon() Function: Draws polygons on a plot. x: x-coordinates of the vertices. y: y-coordinates of the vertices. border: Border color. col: Fill color. lty: Line type for the border. lwd: Line width of the border. Basic Example: Drawing a simple polygon. Complex Polygons: Creating polygons with more vertices. Highlighting Areas: Using polygons to emphasize regions. Adding to Existing Plots: Incorporating polygons into existing plots. Area Plots: Creating area plots or density plots with polygons.

Adding a Polygon with the polygon() Function in R Lire la suite »

Changing the Range of Axes with xlim and ylim with R

Changing the Range of Axes with xlim and ylim Understanding xlim and ylim xlim: Specifies the range of the x-axis. ylim: Specifies the range of the y-axis. Both options accept a numeric vector with two values: c(min, max): The minimum and maximum values of the axis. Using xlim and ylim in the plot() Function You can specify the ranges of the x-axis and y-axis directly when creating a plot using the plot() function. Example:  # Generate example data x <- 1:10 y <- x^2 # Create a plot with default axis ranges plot(x, y, main = “Default Axis Ranges”) # Create a plot with customized x-axis and y-axis ranges plot(x, y, main = “Customized Axis Ranges”, xlim = c(0, 12), ylim = c(0, 120)) xlim = c(0, 12): Sets the x-axis to range from 0 to 12. ylim = c(0, 120): Sets the y-axis to range from 0 to 120. Adjusting Axis Ranges After Plot Creation You can also adjust the axis ranges of an existing plot by using functions like axis() and plot.window(). Example:  # Create a basic plot with default ranges plot(x, y, main = “Plot with Adjustable Ranges”) # Adjust the x-axis and y-axis ranges after plot creation plot.window(xlim = c(0, 12), ylim = c(0, 120)) axis(1, at = seq(0, 12, by = 2))  # Custom x-axis axis(2, at = seq(0, 120, by = 20))  # Custom y-axis plot.window(): Adjusts the plotting region. axis(): Adds custom axis ticks and labels. Using xlim and ylim for Zooming By setting xlim and ylim, you can zoom in on a specific region of your data. Example:  # Generate example data with a large range x <- 1:100 y <- x^2 # Zoom in on a specific region of the data plot(x, y, main = “Zoomed-in View”, xlim = c(30, 70), ylim = c(900, 4900)) xlim = c(30, 70): Zooms in on the x-axis range from 30 to 70. ylim = c(900, 4900): Zooms in on the y-axis range from 900 to 4900. Handling Missing Values and Outliers When adjusting axis ranges, you may want to handle missing values and outliers to ensure that the plot remains informative. Example:  # Generate data with outliers x <- 1:10 y <- c(1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 1000) # Create a plot with customized ranges to handle outliers plot(x, y, main = “Handling Outliers”, xlim = c(0, 12), ylim = c(0, 150)) xlim = c(0, 12): Ensures the x-axis accommodates the full range of data. ylim = c(0, 150): Adjusts the y-axis to handle extreme values. Combining xlim and ylim with Other Plotting Parameters You can combine xlim and ylim with other plotting parameters for a more customized plot. Example:  # Generate example data x <- 1:10 y <- x^2 # Create a plot with customized axis ranges, colors, and point types plot(x, y, main = “Customized Plot”, xlim = c(0, 12), ylim = c(0, 120),      col = “blue”, pch = 16, lty = 2) # Add lines and text abline(h = 50, col = “red”, lty = 3) text(6, 60, “Annotation”, cex = 1.5) col = “blue”: Sets the color of the points. pch = 16: Uses filled circles for points. lty = 2: Adds dashed lines to the plot. abline(): Adds a horizontal line at y = 50. text(): Adds annotation text. Summary xlim and ylim Parameters: Control the ranges of the x and y axes. xlim = c(min, max): Range of the x axis. ylim = c(min, max): Range of the y axis. Customizing Axis Ranges: Specify ranges when creating the chart with plot(). Post-Creation Adjustment: Use plot.window() and axis() to adjust ranges and ticks after the chart is created. Zoom to a Specific Region: Adjust ranges to zoom in on specific regions of the data. Missing Values ​​and Outliers: Adjust ranges to handle extreme values ​​and outliers. Combine with Other Parameters: Combine xlim and ylim with other parameters to further customize your charts.

Changing the Range of Axes with xlim and ylim with R Lire la suite »

Changing Character Sizes with cex in R

Changing Character Sizes with cex Understanding cex The cex parameter is a scaling factor that multiplies the default size of text or symbols. cex Value: cex = 1: Represents the default size. cex < 1: Reduces the size below the default. cex > 1: Increases the size above the default. Changing Text Sizes You can use cex to adjust the size of text in various plot elements, such as titles, axis labels, and annotation text. Example:  # Create a basic plot with default text size plot(1:10, 1:10, main = “Default Text Size”, xlab = “X Axis”, ylab = “Y Axis”) # Add text with increased size text(x = 5, y = 5, labels = “Big Text”, cex = 2, col = “red”) cex = 2: Increases the size of the annotation text to twice the default size. Example with Axis Labels:  # Create a plot with increased axis label size plot(1:10, 1:10, main = “Increased Axis Label Size”, xlab = “X Axis”, ylab = “Y Axis”, cex.lab = 1.5) cex.lab = 1.5: Increases the size of axis labels by 50%. Changing Symbol Sizes You can use cex to adjust the size of plotting symbols (e.g., points) in the plot. Example:  # Plot points with default size plot(1:10, 1:10, main = “Default Point Size”) # Plot points with increased size plot(1:10, 1:10, main = “Increased Point Size”, cex = 2) cex = 2: Increases the size of the points to twice the default size. Changing Text Sizes in Legend You can use cex to adjust the size of text within a legend. Example:  # Create a plot with a legend plot(1:10, 1:10, main = “Legend Text Size”, pch = 16) # Add a legend with increased text size legend(“topright”, legend = c(“Data Points”), pch = 16, cex = 1.5) cex = 1.5: Increases the size of the legend text by 50%. Using cex with Multiple Parameters You can use cex with multiple parameters to control different aspects of text and symbols in the plot. Example:  # Create a plot with varying sizes for title, axis labels, and points plot(1:10, 1:10, main = “Custom Sizes”, xlab = “X Axis”, ylab = “Y Axis”,      cex.main = 2, cex.lab = 1.5, cex.axis = 1.2, cex = 1.5) # Add text with a different size text(5, 5, “Custom Size”, cex = 2) cex.main = 2: Increases the size of the main title. cex.lab = 1.5: Increases the size of the axis labels. cex.axis = 1.2: Increases the size of the axis numbers. cex = 1.5: Increases the size of the plotting symbols. Combining cex with Other Plotting Parameters You can combine cex with other graphical parameters to achieve more customized plots. Example:  # Create a plot with customized text size, symbols, and colors plot(1:10, 1:10, main = “Customized Plot”, xlab = “X Axis”, ylab = “Y Axis”,      cex.main = 2, cex.lab = 1.5, cex.axis = 1.2, cex = 1.5, pch = 19, col = “blue”) # Add text with different size and color text(5, 5, “Important Point”, cex = 2, col = “red”) pch = 19: Uses filled circles for points. col = “blue”: Sets the color of the points. text(): Adds annotation with increased size and color. Summary cex Parameter: Controls the size of text and symbols.  cex < 1: Decreases the size.  cex > 1: Increases the size. Change Text Sizes: Use cex to adjust the size of titles, axis labels, and annotation text. Change Symbol Sizes: Use cex to adjust the size of plot symbols. Change Legend Sizes: Use cex to adjust the size of text in the legend. Use cex with Multiple Parameters: Control different sizes for titles, labels, axes, and symbols at once. Combine cex with Other Parameters: Customize your charts further by combining cex with other chart options.

Changing Character Sizes with cex in R Lire la suite »

Restoring a Plot in R

Restoring a Plot in R Saving and Restoring Plots To restore a plot, you need to save it first. You can save plots in various formats using functions like pdf(), png(), or jpeg(). Saving a Plot:  # Save a plot as a PNG file png(“plot.png”) plot(x, y, main = “Saved Plot”, xlab = “X”, ylab = “Y”) dev.off()  # Close the device to save the plot Restoring (Loading) a Plot: To restore or reuse a plot, you need to reload it from the saved file. Note that once a plot is saved as an image file, it cannot be edited in R directly. You can only view or display it. Displaying a Saved Plot Image:  # Load and display a saved plot image library(png) img <- readPNG(“plot.png”) grid::grid.raster(img) Redrawing a Plot from Saved Data If you have the data used to create the plot, you can redraw it by re-running the plotting commands. This is particularly useful if you want to make modifications to the plot. Example of Redrawing:  # Original plot creation x <- 1:10 y <- x^2 plot(x, y, main = “Original Plot”, xlab = “X”, ylab = “Y”) # Redrawing the same plot # Re-run the same plot commands plot(x, y, main = “Redrawn Plot”, xlab = “X”, ylab = “Y”) Using recordPlot() and replayPlot() R provides functions to save and restore plots within a single R session using recordPlot() and replayPlot(). Recording a Plot:  # Record a plot plot(x, y, main = “Recorded Plot”, xlab = “X”, ylab = “Y”) recorded_plot <- recordPlot() Restoring a Plot:  # Restore the recorded plot replayPlot(recorded_plot) recordPlot(): Captures the current plot, storing it as an object. replayPlot(): Replays the captured plot object, restoring the plot. Using dev.control() for Interactive Sessions In interactive R sessions, you can use dev.control() to manage plot devices. Example:  # Open a new plotting device dev.new() # Create a plot plot(x, y, main = “Interactive Session Plot”, xlab = “X”, ylab = “Y”) # Use dev.control to manage the device dev.control(“inhibit”)  # Stop automatic updating of the plot dev.control(“enable”)   # Re-enable automatic updates dev.control(“inhibit”): Temporarily stops updates to the plot device. dev.control(“enable”): Resumes plot updates. Reusing Plot Code for Different Data You can create reusable functions to generate plots for different datasets, making it easier to restore or regenerate plots. Example:  # Define a plotting function plot_data <- function(x, y, title = “Plot”, xlabel = “X”, ylabel = “Y”) {   plot(x, y, main = title, xlab = xlabel, ylab = ylabel) } # Use the function with different data x1 <- 1:10 y1 <- x1^2 plot_data(x1, y1, title = “Plot 1”) x2 <- 1:10 y2 <- x2^3 plot_data(x2, y2, title = “Plot 2”) plot_data(): A function that generates plots based on provided data and labels. Summary Saving and Restoring Plots: Save plots using functions like png(), pdf(), or jpeg(). Display saved images using packages like png. Redrawing Plots: Recreate plots by re-running the plotting commands with the original data. Using recordPlot() and replayPlot(): Save and restore plots within a session. Managing Plot Devices: Use dev.control() to manage interactive plotting sessions. Reusable Plot Code: Create functions to generate plots for different datasets easily.

Restoring a Plot in R Lire la suite »

The text() Function with R

The text() Function Basic Usage The text() function adds text to an existing plot at specified coordinates. Basic Syntax:  text(x, y, labels, pos, offset, cex, col, font) x: The x-coordinate where the text will be placed. y: The y-coordinate where the text will be placed. labels: The text to display. pos: The position of the text relative to the coordinates (1 for below, 2 for left, 3 for above, 4 for right). offset: Offset of the text from the specified coordinates. cex: Expansion factor to adjust the text size. col: Color of the text. font: Font style (1 for normal, 2 for bold, 3 for italic, 4 for underline). Example:  # Create a basic plot x <- 1:10 y <- x^2 plot(x, y, main = “Text Annotation Example”, xlab = “X”, ylab = “Y”) # Add text text(5, 25, “Important Point”, cex = 1.2, col = “red”, pos = 4) text(5, 25, “Important Point”, …): Places the text “Important Point” at coordinates (5, 25). cex = 1.2: Increases the text size. col = “red”: Sets the text color to red. pos = 4: Places the text to the right of the coordinates. Adding Text to Specific Points You can use text() to label specific points on the plot. Example:  # Create a basic plot plot(x, y, main = “Text on Specific Points”, xlab = “X”, ylab = “Y”) # Add text for each point text(x, y, labels = paste(“(“, x, “,”, y, “)”, sep = “”), pos = 1, cex = 0.8) labels = paste(“(“, x, “,”, y, “)”, sep = “”): Creates labels with the coordinates of the points. pos = 1: Places the text below the coordinates of the points. Adjusting Text Size and Position Use cex and pos to adjust the text size and position. Example:  # Create a basic plot plot(x, y, main = “Adjust Text Size and Position”, xlab = “X”, ylab = “Y”) # Add text with different sizes and positions text(5, 25, “Large Text”, cex = 2, col = “blue”, pos = 3) # Larger text above text(7, 50, “Small Text”, cex = 0.6, col = “green”, pos = 1) # Smaller text below cex = 2: Increases the text size. cex = 0.6: Decreases the text size. Using Text for Annotations Add text annotations to highlight specific parts of the plot, such as points of interest or key observations. Example:  # Create a basic plot plot(x, y, main = “Annotations with Text”, xlab = “X”, ylab = “Y”) # Add an annotation text(8, 64, “Maximal Here”, cex = 1.5, col = “darkred”, pos = 3, font = 2) font = 2: Makes the text bold. pos = 3: Places the text above the specified point. Adding Text in Relative Coordinates You can place text using relative coordinates for proportional positioning. Example:  # Create a basic plot plot(x, y, main = “Text in Relative Coordinates”, xlab = “X”, ylab = “Y”) # Add text with relative coordinates text(x = max(x) * 0.5, y = max(y) * 0.5, “Central Text”, cex = 1.2, col = “purple”) x = max(x) * 0.5: Places the text at the midpoint of the x-axis. y = max(y) * 0.5: Places the text at the midpoint of the y-axis. Summary Basic Usage: Use text() to add text at specified coordinates on a plot. Text on Points: Label specific points with coordinates. Adjust Size and Position: Modify text size (cex) and position (pos). Annotations: Use text() to annotate parts of the plot or highlight key points. Relative Coordinates: Place text using proportional coordinates for dynamic positioning.

The text() Function with R Lire la suite »

The legend() Function with R

The legend() Function Basic Usage The legend() function adds a legend to an existing plot, providing a key to interpret the various graphical elements. The basic syntax is:  legend(x, y, legend, col, pch, lty, lwd, cex, bg) x: The x-coordinate or position for the legend. y: The y-coordinate or position for the legend. legend: A vector of text strings to describe the legend items. col: A vector of colors corresponding to the items in the legend. pch: A vector of plotting characters (symbols) corresponding to the items. lty: A vector of line types (e.g., solid, dashed) corresponding to the items. lwd: A vector of line widths for the lines in the legend. cex: A numerical value to adjust the size of the text in the legend. bg: Background color of the legend box. Adding a Simple Legend Here’s an example of adding a basic legend to a plot with different colors and symbols. Example:  # Create a base plot x <- 1:10 y1 <- x y2 <- x^2 plot(x, y1, type = “b”, col = “blue”, pch = 16, lty = 1, ylim = c(0, 100),      xlab = “X”, ylab = “Y”, main = “Example with Legend”) # Add another series lines(x, y2, col = “red”, pch = 17, lty = 2) # Add a legend legend(“topleft”, legend = c(“Linear”, “Quadratic”),        col = c(“blue”, “red”), pch = c(16, 17), lty = c(1, 2)) legend(“topleft”, …): Places the legend in the top-left corner. legend = c(“Linear”, “Quadratic”): Labels for each series. col = c(“blue”, “red”): Colors for the points or lines. pch = c(16, 17): Symbols used in the plot. lty = c(1, 2): Line types for each series. Customizing the Legend Appearance You can customize the legend’s appearance using additional arguments. Example:  # Create a base plot plot(x, y1, type = “b”, col = “blue”, pch = 16, lty = 1, ylim = c(0, 100),      xlab = “X”, ylab = “Y”, main = “Customized Legend”) # Add another series lines(x, y2, col = “red”, pch = 17, lty = 2) # Add a customized legend legend(“topright”, legend = c(“Linear”, “Quadratic”),        col = c(“blue”, “red”), pch = c(16, 17), lty = c(1, 2),        cex = 0.8, bg = “lightgray”, box.col = “black”) cex = 0.8: Reduces the text size in the legend. bg = “lightgray”: Sets the background color of the legend box. box.col = “black”: Sets the color of the box around the legend. Positioning the Legend The x and y arguments in legend() can be specified as positions or coordinates. String Positions: Use strings like “topright”, “bottomleft”, “center” to place the legend in standard locations. Numeric Coordinates: Specify exact coordinates for precise positioning. Example:  # Create a base plot plot(x, y1, type = “b”, col = “blue”, pch = 16, lty = 1, ylim = c(0, 100),      xlab = “X”, ylab = “Y”, main = “Legend Positioning”) # Add another series lines(x, y2, col = “red”, pch = 17, lty = 2) # Add a legend at a specific coordinate legend(8, 80, legend = c(“Linear”, “Quadratic”),        col = c(“blue”, “red”), pch = c(16, 17), lty = c(1, 2)) legend(8, 80, …): Places the legend at the coordinates (8, 80) on the plot. Using Legends for Multiple Plot Types Legends can describe different types of graphical elements, including points, lines, and more. Example:  # Create a base plot plot(x, y1, type = “b”, col = “blue”, pch = 16, lty = 1, ylim = c(0, 100),      xlab = “X”, ylab = “Y”, main = “Legend for Different Plot Types”) # Add a series with lines lines(x, y2, col = “red”, lty = 2) # Add a series with points only points(x, y1 + 5, col = “green”, pch = 18) # Add a legend for all plot types legend(“topright”, legend = c(“Linear – Lines”, “Quadratic – Lines”, “Points Only”),        col = c(“blue”, “red”, “green”), pch = c(16, NA, 18), lty = c(1, 2, NA)) pch = c(16, NA, 18): NA indicates that no symbol is used (for lines). lty = c(1, 2, NA): NA indicates that no line type is used (for points only). Summary Basic Usage: Use legend() to add a legend to an existing plot. Customizing Appearance: Adjust the text size (cex), background color (bg), and box color (box.col). Positioning: Use standard string positions or numeric coordinates. Multiple Plot Types: Create legends for different plot elements like lines, points, and more.

The legend() Function with R Lire la suite »

Smoothing Points with lowess() and loess() with R

Smoothing Points with lowess() and loess() Understanding lowess() and loess() lowess(): Stands for “Locally Weighted Scatterplot Smoothing.” It fits a smooth curve to the data using locally weighted regression. It’s particularly useful for exploring trends in data. loess(): Stands for “Locally Estimated Scatterplot Smoothing.” It provides a more flexible, polynomial-based smoothing and can handle more complex relationships. Using lowess() Syntax:  lowess(x, y = NULL, f = 2/3, delta = NULL, iter = 3, …) x: Numeric vector of x-coordinates. y: Numeric vector of y-coordinates (if x is a matrix, y can be omitted). f: The smoothing parameter (between 0 and 1). Default is 2/3. delta: Bandwidth parameter for large datasets. iter: Number of iterations for robust fitting (default is 3). Example:  # Generate example data x <- 1:20 y <- x + rnorm(20) # Create a basic plot plot(x, y, main = “LOWESS Smoothing Example”) # Apply LOWESS smoothing smoothed <- lowess(x, y) # Add the smoothed line to the plot lines(smoothed, col = “blue”) smoothed: Contains the smoothed values returned by lowess(). lines(): Adds the smoothed line to the existing plot. Using loess() Syntax:  loess(formula, data, span = 0.75, degree = 2, family = “symmetric”, …) formula: A formula describing the model (e.g., y ~ x). data: Data frame containing the variables. span: The smoother parameter, analogous to f in lowess() (default is 0.75). degree: Degree of the local polynomial (default is 2, which fits a quadratic model). family: Type of smoothing (e.g., “symmetric” or “adaptative”). Example:  # Generate example data data <- data.frame(x = 1:20, y = (1:20) + rnorm(20)) # Create a basic plot plot(data$x, data$y, main = “LOESS Smoothing Example”) # Apply LOESS smoothing fit <- loess(y ~ x, data = data) # Predict values pred <- predict(fit) # Add the smoothed line to the plot lines(data$x, pred, col = “red”) fit: LOESS model fitted to the data. predict(): Predicts values based on the LOESS model. Comparing lowess() and loess() lowess() is simpler and less flexible but is often sufficient for basic smoothing tasks. loess() provides more control and can handle more complex data relationships. Comparison Example:  # Generate example data x <- 1:30 y <- sin(x / 2) + rnorm(30) # Create a basic plot plot(x, y, main = “Comparing LOWESS and LOESS”) # Apply LOWESS smoothing lowess_smoothed <- lowess(x, y) lines(lowess_smoothed, col = “blue”, lty = 1) # Apply LOESS smoothing loess_fit <- loess(y ~ x) loess_smoothed <- predict(loess_fit) lines(x, loess_smoothed, col = “red”, lty = 2) # Add a legend legend(“topright”, legend = c(“LOWESS”, “LOESS”), col = c(“blue”, “red”), lty = c(1, 2)) lty: Line type to differentiate between LOWESS and LOESS lines. Adjusting Parameters f (for lowess()) and span (for loess()) control the amount of smoothing. Smaller values result in more localized smoothing, while larger values result in more global smoothing. Example:  # Generate example data x <- 1:50 y <- sin(x / 5) + rnorm(50) # Basic plot plot(x, y, main = “Adjusting Smoothing Parameters”) # LOWESS with different smoothing parameter lowess_smoothed_1 <- lowess(x, y, f = 0.2) lines(lowess_smoothed_1, col = “blue”, lty = 1) # LOESS with different span loess_fit_1 <- loess(y ~ x, span = 0.2) loess_smoothed_1 <- predict(loess_fit_1) lines(x, loess_smoothed_1, col = “red”, lty = 2) Visualizing the Effect of Smoothing To understand how smoothing affects the plot, you can overlay multiple smoothing results or compare smoothed curves with the original data. Example:  # Generate example data x <- 1:40 y <- cos(x / 3) + rnorm(40) # Basic plot plot(x, y, main = “Effect of Smoothing Parameters”) # LOWESS with default smoothing parameter lowess_smoothed_default <- lowess(x, y) lines(lowess_smoothed_default, col = “blue”, lty = 1) # LOESS with a large span loess_fit_large_span <- loess(y ~ x, span = 1) loess_smoothed_large_span <- predict(loess_fit_large_span) lines(x, loess_smoothed_large_span, col = “red”, lty = 2) # LOESS with a small span loess_fit_small_span <- loess(y ~ x, span = 0.1) loess_smoothed_small_span <- predict(loess_fit_small_span) lines(x, loess_smoothed_small_span, col = “green”, lty = 3) # Add a legend legend(“topright”, legend = c(“LOWESS”, “LOESS (Large Span)”, “LOESS (Small Span)”),        col = c(“blue”, “red”, “green”), lty = c(1, 2, 3)) Summary lowess(): Simple, robust smoothing for exploring trends. f: Smoothing parameter (default 2/3). loess(): Flexible polynomial-based smoothing for complex data. span: Smoothing parameter (default 0.75). degree: Degree of the local polynomial (default 2). Comparison: lowess() is simpler; loess() offers more flexibility. Parameter Adjustment: Control the level of smoothing with f and span. Visualization: Compare different smoothing results to understand effects.

Smoothing Points with lowess() and loess() with R Lire la suite »

The function abline() with R

The function abline() Syntax of abline()  abline(a = NULL, b = NULL, h = NULL, v = NULL, reg = NULL,        coef = NULL, col = NULL, lty = NULL, lwd = NULL, …) a: Intercept of the line (for y = a + bx). b: Slope of the line (for y = a + bx). h: Numeric value(s) for horizontal lines (y = h). v: Numeric value(s) for vertical lines (x = v). reg: A regression object (e.g., from lm()). coef: Coefficients of a line (a and b). col: Color of the line. lty: Line type (e.g., 1 for solid, 2 for dashed). lwd: Line width. …: Additional graphical parameters. Examples Adding a Horizontal Line  x <- 1:10 y <- x^2 plot(x, y, main = “Plot with Horizontal Line”, xlab = “X”, ylab = “Y”) abline(h = 50, col = “blue”, lty = 2, lwd = 2) h = 50: Adds a horizontal line at y = 50. col = “blue”: Line color. lty = 2: Dashed line. lwd = 2: Line width. Adding a Vertical Line  plot(x, y, main = “Plot with Vertical Line”, xlab = “X”, ylab = “Y”) abline(v = 5, col = “red”, lty = 3, lwd = 2) v = 5: Adds a vertical line at x = 5. col = “red”: Line color. lty = 3: Dotted line. lwd = 2: Line width. Adding a Line with Slope and Intercept  plot(x, y, main = “Plot with Line by Slope and Intercept”, xlab = “X”, ylab = “Y”) abline(a = 10, b = 1, col = “green”, lty = 1, lwd = 2) a = 10: y-intercept. b = 1: Slope of the line. col = “green”: Line color. lty = 1: Solid line. lwd = 2: Line width. Adding a Regression Line  model <- lm(y ~ x) plot(x, y, main = “Plot with Regression Line”, xlab = “X”, ylab = “Y”) abline(model, col = “purple”, lty = 1, lwd = 2) model: Linear model object. abline(model): Adds the regression line from the model. col = “purple”: Line color. lty = 1: Solid line. lwd = 2: Line width. Adding Multiple Lines  plot(x, y, main = “Plot with Multiple Lines”, xlab = “X”, ylab = “Y”) abline(h = c(20, 60), col = c(“blue”, “red”), lty = c(2, 3), lwd = 2) h = c(20, 60): Adds two horizontal lines. col = c(“blue”, “red”): Colors for each line. lty = c(2, 3): Line types for each line. lwd = 2: Line width for both lines. Notes abline() works best with simple linear functions. For more complex lines or shapes, consider using lines() or curve(). Customization: You can combine abline() with other functions (like points() or text()) for more complex plots.

The function abline() with R Lire la suite »

The function plot() with R

The function plot() Basic Syntax of plot() The basic syntax of plot() is:  plot(x, y, type = “p”, main = NULL, xlab = NULL, ylab = NULL,      xlim = NULL, ylim = NULL, pch = NULL, col = NULL, lty = NULL,      lwd = NULL, cex = NULL, … ) x, y: Data vectors for the X and Y axes. type: Type of plot (“p” for points, “l” for lines, “b” for both points and lines, etc.). main: Title of the plot. xlab, ylab: Labels for the X and Y axes. xlim, ylim: Limits for the X and Y axes. pch: Symbol used for points. col: Color of points or lines. lty: Line type (1 for solid, 2 for dashed, etc.). lwd: Line width. cex: Text or point size scaling. …: Additional arguments to customize the plot. Detailed Examples Scatter Plot  x <- 1:10 y <- x^2 # Basic scatter plot with blue points plot(x, y, type = “p”, main = “Scatter Plot”, xlab = “X”, ylab = “Y”, pch = 19, col = “blue”) type = “p”: Points only. pch = 19: Filled circles. col = “blue”: Point color. Line Plot  # Line plot with a red line plot(x, y, type = “l”, main = “Line Plot”, xlab = “X”, ylab = “Y”, col = “red”, lwd = 2) type = “l”: Lines only. col = “red”: Line color. lwd = 2: Line width. Plot with Points and Lines  # Plot with both points and lines plot(x, y, type = “b”, main = “Plot with Points and Lines”, xlab = “X”, ylab = “Y”, pch = 17, col = “green”, lty = 1) type = “b”: Both points and lines. pch = 17: Triangle symbols. col = “green”: Color of points and lines. Plot with Custom Limits  # Plot with customized axis limits plot(x, y, type = “b”, main = “Plot with Custom Limits”, xlab = “X”, ylab = “Y”, xlim = c(0, 12), ylim = c(0, 120), col = “purple”, lty = 2, lwd = 1.5) xlim = c(0, 12): X-axis limits from 0 to 12. ylim = c(0, 120): Y-axis limits from 0 to 120. lty = 2: Dashed line. lwd = 1.5: Line width. Plot with Text and Annotations  # Plot with text annotations plot(x, y, type = “b”, main = “Plot with Annotations”, xlab = “X”, ylab = “Y”, col = “orange”) text(x, y, labels = round(y, 1), pos = 3, cex = 0.8, col = “blue”) text(x, y, labels, pos, cex, col): Adds text to points. labels = round(y, 1): Text near points. pos = 3: Text above points. cex = 0.8: Text size. col = “blue”: Text color. Multi-Dimensional Plots with plot() For more complex plots, you can use plot() in combination with other functions or explore packages like ggplot2 for advanced plotting. Additional Notes par(): Used to set graphical parameters such as margins, layout. For example, par(mfrow = c(2, 2)) divides the plotting area into a 2×2 grid. axis() and legend(): Add customized axes and legends.

The function plot() with R Lire la suite »

Regular Expressions Overview with R

Regular Expressions Overview Regular expressions (regex) are sequences of characters that define a search pattern. They are extremely powerful for performing complex string operations, such as searching, validating, manipulating, and substituting text. Regular Expression Syntax Regular expressions use a specific syntax to describe patterns. Here’s a breakdown of the basic components: Literal Characters a: Matches the character ‘a’. abc: Matches the exact string “abc”. Metacharacters .: Matches any single character except a newline. Example: “a.c” matches “abc”, “a2c”, “a c”, etc. ^: Matches the start of a string. Example: “^abc” matches “abc” only if “abc” is at the start of the string. $: Matches the end of a string. Example: “abc$” matches “abc” only if “abc” is at the end of the string. *: Matches zero or more occurrences of the preceding character. Example: “a*b” matches “b”, “ab”, “aab”, “aaab”, etc. +: Matches one or more occurrences of the preceding character. Example: “a+b” matches “ab”, “aab”, “aaab”, etc., but not “b”. ?: Matches zero or one occurrence of the preceding character. Example: “a?b” matches “b” or “ab”. {n}: Matches exactly n occurrences of the preceding character. Example: “a{3}” matches “aaa”. {n,}: Matches at least n occurrences of the preceding character. Example: “a{2,}” matches “aa”, “aaa”, “aaaa”, etc. {n,m}: Matches between n and m occurrences of the preceding character. Example: “a{2,4}” matches “aa”, “aaa”, or “aaaa”. Character Classes [abc]: Matches any one of ‘a’, ‘b’, or ‘c’. Example: “[abc]” matches “a”, “b”, or “c”. [^abc]: Matches any character except ‘a’, ‘b’, or ‘c’. Example: “[^abc]” matches “d”, “1”, etc. [a-z]: Matches any character between ‘a’ and ‘z’ (lowercase). Example: “[a-z]” matches “b”, “c”, “x”, etc. [A-Z]: Matches any character between ‘A’ and ‘Z’ (uppercase). Example: “[A-Z]” matches “D”, “X”, etc. [0-9]: Matches any digit from 0 to 9. Example: “[0-9]” matches “3”, “7”, etc. Meta-Classes \d: Matches a digit (equivalent to [0-9]). Example: “\d” matches “5”, “0”, etc. \D: Matches any non-digit character (equivalent to [^0-9]). Example: “\D” matches “a”, “$”, etc. \w: Matches a word character (equivalent to [a-zA-Z0-9_]). Example: “\w” matches “a”, “2”, “_”, etc. \W: Matches any non-word character (equivalent to [^a-zA-Z0-9_]). Example: “\W” matches “!”, “#”, etc. \s: Matches any whitespace character (space, tab, newline). Example: “\s” matches ” “, “\t”, “\n”, etc. \S: Matches any non-whitespace character. Example: “\S” matches “a”, “1”, etc. Groups and Captures (abc): Defines a capturing group that matches the string “abc”. This group can be referenced later or used to extract substrings. Example: “(abc)+” matches “abc”, “abcabc”, etc. (?:abc): Defines a non-capturing group. It matches “abc” but does not capture it for later references. Example: “(?:abc)+” matches “abc”, “abcabc”, but does not create a capturing group. (?<name>abc): Defines a named capturing group “name” that matches “abc”. You can refer to this group by its name. Example: (?<digit>\d) matches a digit and can be referenced as “digit”. Using Regular Expressions in R Regular expressions are used in various R functions to search, manipulate, or validate strings. Here are some examples: Example 1: grep()  # Find the indices of strings containing “abc” grep(“abc”, c(“abc”, “def”, “abcd”), value = FALSE) # [1] 1 4 Example 2: grepl()  # Check if the string contains “abc” grepl(“abc”, c(“abc”, “def”, “abcd”)) # [1] TRUE FALSE TRUE Example 3: sub() and gsub()  # Replace the first occurrence of “abc” with “XYZ” sub(“abc”, “XYZ”, “abc def abc”) # [1] “XYZ def abc” # Replace all occurrences of “abc” with “XYZ” gsub(“abc”, “XYZ”, “abc def abc”) # [1] “XYZ def XYZ” Example 4: regexpr() and gregexpr()  # Find the first occurrence of the pattern “\\d+” regexpr(“\\d+”, “There are 123 apples and 456 oranges”) # [1] 12 # attr(,”match.length”) # [1] 3 # Find all occurrences of the pattern “\\d+” gregexpr(“\\d+”, “There are 123 apples and 456 oranges”) # [[1]] # [1] 12 29 # attr(,”match.length”) # [1] 3 3  Practical Tips Escape Special Characters: To search for special characters (like ., *, ?), you need to escape them with a backslash (\), for example, \\. to search for a period. Test Your Regex: Use online regex testers and debuggers to refine and test your regular expressions before using them in code. Performance: Regular expressions can be complex and potentially slow on large texts. Simplify patterns where possible to improve performance.

Regular Expressions Overview with R Lire la suite »