Mostrando entradas con la etiqueta geom_point. Mostrar todas las entradas
Mostrando entradas con la etiqueta geom_point. Mostrar todas las entradas

2021-03-09

How to highlight specific data points in a scatter plot with ggplot2

Problem

We would like to highlight specific data points in a scatter plot created with ggplot2. In our example, we will use the mpg dataset (Fuel economy data from 1999 and 2008 for 38 popular models of car). We want to highlight in red and a larger point size those data points whose displ (engine displacement) are greater than 5 and hwy (highway miles per gallon) greater than 20.

Solution

  • Option 1
  • We add the conditions for both attributes, colour and size, inside geom_point. Then we control manually those using scale_colour_manual and scale_size_manual respectively. Finally, we remove the legend.

    ggplot(data = mpg) + 
      geom_point(mapping = aes(x = displ, y = hwy, colour = displ > 5 & hwy > 20, size = displ > 5 & hwy > 20)) + 
      scale_colour_manual(values = c("black", "red")) + 
      scale_size_manual(values =c(1.5, 3))+
      theme(legend.position = "none")
    
  • Option 2
  • We create two layers of data points using geom_point. The first layer include all data points in black (by default but e). The second layer adds the points we would like to highlight in red with a larger point size.

    ggplot(data = mpg) + 
      geom_point(mapping = aes(x = displ, y = hwy), colour= "black") +
      geom_point(data = subset(mpg, displ > 5 & hwy > 20), aes(x = displ, y = hwy), colour= "red", size = 3)
     
    In ggplot2 the layers are added sequentially. If we change the order of the layers, we would get the following result.

    ggplot(data = mpg) + 
       geom_point(data = subset(mpg, displ > 5 & hwy > 20), aes(x = displ, y = hwy), colour= "red", size = 3) +
       geom_point(mapping = aes(x = displ, y = hwy), colour= "black")
     

    2021-02-09

    How to set tick labels to the edges of a continuous ggplot2 legend

    Title

    Problem

    We want to show the minimum and maximum values in the legend of our plot in ggplot2.

    library(ggplot2)
    d <- subset(diamonds, price >= 257 & price <= 8888)
    ggplot(d, aes(depth, carat, colour = price)) +
      geom_point() +
      scale_colour_gradient(limits = c(257, 8888))
    

    The legend shows values from 2.000 al 8.000 but we do not know the minimum and the maximum values.

    Solution

    Within scale_colour_gradient, we pass the arguments breaks and labels.

    ggplot(d, aes(depth, carat, colour = price)) +
      geom_point() +
      scale_colour_gradient(limits = c(257, 8888), 
                            breaks = c(257, 2000, 4000, 6000, 8000, 8888),
                            labels = c(257, 2000, 4000, 6000, 8000, 8888))
    

    Now we have added to the legend the minimum 257 and the maximum 8.888 values.

    Notes

    Instead of using the default colour scale colours from light blue to dark blue, we can adjust colour choices with the arguments low and high.

    ggplot(d, aes(depth, carat, colour = price)) +
      geom_point() +
      scale_colour_gradient(limits = c(257, 8888), 
                            breaks=c(257, 2000, 4000, 6000, 8000, 8888),
                            labels=c(257, 2000, 4000, 6000, 8000, 8888), low = "red")
    

    References

    2019-10-03

    How to add a text box to a plot in R

    Problem

    We want to add a text box to a plot in R. First, we will use a very convoluted code to get it done.

    # A plot
    plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")
    
    # Text box parameters
    myText <- "some Text"
    posCoordsVec <- c(0.5, 0.5)
    cex <- 2
    
    # Rectangle
    textHeight <- graphics::strheight(myText, cex = cex)
    textWidth <- graphics::strwidth(myText, cex = cex)
    pad <- textHeight*0.3
    rect(xleft = posCoordsVec[1] - textWidth/2 - pad, 
            ybottom = posCoordsVec[2] - textHeight/2 - pad, 
            xright = posCoordsVec[1] + textWidth/2 + pad, 
            ytop = posCoordsVec[2] + textHeight/2 + pad,
            col = "lightblue", border = NA)
    
    # Text coordinates
    text(posCoordsVec[1], posCoordsVec[2], myText, cex = cex)
    

    Solution

    • Base graphics
    • We use the function legend, same colour for the box line (box.col) and the background (bg), adjusting the text inside with the argument adj.

      plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")
      legend(0.4, 0.5, "Some text", box.col = "lightblue", bg = "lightblue", adj = 0.2)
      
    • ggpplot2
    • With ggplot2 we need the function geom_label. The text will be automatically aligned inside the box, we remove the borders with label.size = NA.

      library(ggplot2)
      df <- data.frame(x = runif(1000), y = runif(1000))
      ggplot(data = df, aes(x = x , y = y))+ 
        geom_point(alpha = 0.2)+
        geom_label(aes(x = 0.5, y = 0.5, label = "Some text"), 
                   fill = "lightblue", label.size = NA, size = 5)
      

    References

    2019-08-10

    Cómo representar una curva logarítmica en R

    Problema

    Queremos ajustar una curva logarítmica a un diagrama de dispersión.

    library(ggplot2)
    ggplot(mpg, aes(displ, hwy)) +
      geom_point()
    

    Solución

    Paquete base

    plot(hwy ~ displ, mpg)
    logEstimate <- lm(hwy ~ log(displ), data = mpg)
    curve(coef(logEstimate)[1] + coef(logEstimate)[2] * log(x), add = TRUE)
    
    ggplot2

    ggplot(mpg, aes(displ, hwy)) +
      geom_point() +
      stat_smooth(method = "lm", formula = y ~ log(x))
    

    Referencias

    How to plot a log curve in R

    Problem

    We want to fit a logarithmic curve to a scatterplot.

    library(ggplot2)
    ggplot(mpg, aes(displ, hwy)) +
      geom_point()
    

    Solution

    Base package

    plot(hwy ~ displ, mpg)
    logEstimate <- lm(hwy ~ log(displ), data = mpg)
    curve(coef(logEstimate)[1] + coef(logEstimate)[2] * log(x), add = TRUE)
    
    ggplot2

    ggplot(mpg, aes(displ, hwy)) +
      geom_point() +
      stat_smooth(method = "lm", formula = y ~ log(x))
    

    References

    2019-01-10

    Loops with ggplot2

    Problem

    We want to create a loop and save plots for each subset of data using ggplot2. Instead of plotting on the same panel using facet_wrap o facet_grid, we'd like to display and save eachplot separately.

    library(tidyverse)
    p <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point()
    p + facet_wrap(vars(Species), scales = "free")
    

    Solution

    We create an empty list to store all plots. Then, we start a loop for each unique element of the variable (column) Species. To keep the same title format, we leave the function facet_wrap.

    # Loop
    plots <- list() # Empty list
    p_list <- unique(iris$Species)
    for (i in seq_along(p_list)) {
      # Plot for each Species
      p <- iris %>% filter(Species == p_list[i]) %>%
        ggplot(aes(Sepal.Length, Sepal.Width)) +
        geom_point() +
        facet_wrap( ~ Species) # Títulos
      plots[[i]] = p
      print(p)
    }
    
    To print the whole plot list or a specific element:

    # Print list
    print(plots)
    # Print an element of the list
    print(plots[[1]])
    

    Related posts

    References

    Nube de datos