The “geom_tile” Function in R

  • Package: ggplot2

  • Purpose: To create a heatmap or a tile plot by filling rectangles with colors based on a continuous variable or specified values.

  • General Class: Data Visualization

  • Required Argument(s):

    • mapping: Specifies the aesthetic mapping.

  • Notable Optional Arguments:

    • width, height: Controls the width and height of the tiles.

    • fill: Sets the color of the tiles.

    • color: Sets the color of the border around the tiles.

    • linetype: Specifies the type of line for the tile borders.

  • Example (with Explanation):

  • # Example Data
    matrix_data <- matrix(1:9, ncol = 3)
    rownames(matrix_data) <- c("Row1", "Row2", "Row3")
    colnames(matrix_data) <- c("Col1", "Col2", "Col3")

    # Load necessary packages
    library(ggplot2)
    library(reshape2)

    # Melt the matrix
    melted_data <- melt(matrix_data)

    # Basic Tile Plot
    ggplot(melted_data, aes(x = Var2, y = Var1, fill = value)) +
    geom_tile(color = "white") +
    scale_fill_gradient(low = "lightblue", high = "darkblue") +
    labs(title = "Basic Tile Plot", x = "Columns", y = "Rows")

  • In this example, the geom_tile function is used to create a basic tile plot. The matrix data is melted into a long format using the melt function from the reshape2 package, and the resulting data frame is used to create the plot. The Var1 and Var2 are mapped to the x and y-axis, and the value variable is used to fill the tiles with colors. The scale_fill_gradient function is employed to define a gradient color scale for the tiles.

Previous
Previous

The “theme_void” Function in R

Next
Next

The “geom_violin” Function in R