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

2020-12-18

How to change the spacing between the legend and the panel in ggplot2

Title

Problema

We want to increase the spacing between the legend and the panel in ggplot2.

library(ggplot2)
xy <- data.frame(x = 1:10, y = 10:1, type = rep(LETTERS[1:2], each=5))
plot <- ggplot(data = xy) +
        geom_point(aes(x = x, y = y, colo r= type))

Solution

We use the argument legend.box.margin to add 20 points to the left.

plot <- plot + theme(legend.box.margin = margin(0, 0, 0, 20))

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-06-06

Spacing between legend keys in ggplot2

Problem

We want to add some spacing between the elements of the legend to the following plot using ggplot2.

library(tidyverse)
mtcars %>%
  mutate(transmission = ifelse(am, "manual", "automatic")) %>%
  ggplot() +
  aes(x = transmission, fill = transmission) +
  geom_bar() +
  labs(fill = NULL) +
  theme(
    #legend.spacing.x = unit(.5, "char"), # adds spacing to the left too
    legend.position = "top",
    legend.justification = c(0, 0),
    legend.title = element_blank(),
    legend.margin = margin(c(5, 5, 5, 0))
  )

Solution

  • First option: spacing between the 4 elements
  • We use legend.spacing.x to add the spacing between the 4 elements the legend's key and text.

    mtcars %>%
      mutate(transmission = ifelse(am, "manual", "automatic")) %>%
      ggplot() +
      aes(x = transmission, fill = transmission) +
      geom_bar() +
      labs(fill = NULL) +
      theme(
        legend.spacing.x = unit(.5, "char"),
        legend.position = "top",
        legend.justification = c(0, 0),
        legend.title = element_blank(),
        legend.margin = margin(c(5, 5, 5, 0)))
    
  • Second option: spacing between the 2 groups automatic and manual
  • We pass the argument margin to he element_text function to add spacing only between the 2 groups, the two types of transmissions automatic and manual, between the text automatic and the key (blue square) of manual

    mtcars %>%
      mutate(transmission = ifelse(am, "manual", "automatic")) %>%
      ggplot() +
      aes(x = transmission, fill = transmission) +
      geom_bar() +
      labs(fill = NULL) +
      theme(legend.position = "top",
        legend.justification = c(0, 0),
        legend.title = element_blank(),
        legend.margin = margin(c(5, 5, 5, 0)),
        legend.text = element_text(margin = margin(r = 10, unit = "pt")))
    

    Related posts

    References

    2018-08-12

    Ajustar espacio entre los elementos de una leyenda en ggplot2

    Problema

    Tenemos el siguiente gráfico en el que deseamos separar los dos elementos de la leyenda: automatic y manual.

    library(tidyverse)
    mtcars %>%
      mutate(transmission = ifelse(am, "manual", "automatic")) %>%
      ggplot() +
      aes(x = transmission, fill = transmission) +
      geom_bar() +
      labs(fill = NULL) +
      theme(
        #legend.spacing.x = unit(.5, "char"), # adds spacing to the left too
        legend.position = "top",
        legend.justification = c(0, 0),
        legend.title = element_blank(),
        legend.margin = margin(c(5, 5, 5, 0))
      )
    

    Solución

  • Primera opción: espacio entre los 4 elementos
  • Empleamos legend.spacing.x que crea un espacio entre los 4 elementos, las muestras de color y los textos.

    mtcars %>%
      mutate(transmission = ifelse(am, "manual", "automatic")) %>%
      ggplot() +
      aes(x = transmission, fill = transmission) +
      geom_bar() +
      labs(fill = NULL) +
      theme(
        legend.spacing.x = unit(.5, "char"),
        legend.position = "top",
        legend.justification = c(0, 0),
        legend.title = element_blank(),
        legend.margin = margin(c(5, 5, 5, 0)))
    
  • Segunda opción: espacio entre los 2 grupos de elementos
  • Empleamos margin dentro de element_text para crear un espacio solamente entre los grupos de elementos, el correspondiente a la serie automatic y el correspondiente a manual.

    mtcars %>%
      mutate(transmission = ifelse(am, "manual", "automatic")) %>%
      ggplot() +
      aes(x = transmission, fill = transmission) +
      geom_bar() +
      labs(fill = NULL) +
      theme(legend.position = "top",
        legend.justification = c(0, 0),
        legend.title = element_blank(),
        legend.margin = margin(c(5, 5, 5, 0)),
        legend.text = element_text(margin = margin(r = 10, unit = "pt")))
    

    Entradas relacionadas

    Referencias

    2017-08-03

    Añadir un cuadro de texto a un gráfico en R

    Problema

    Queremos añadir un cuadro de texto a un gráfico en R. A continuación, podemos ver una primera solución, pero el código es demasiado verboso y alambicado.

    # Un gráfico
    plot(x = runif(1000), y = runif(1000), type = "p", pch = 16, col = "#40404050")
    
    ## Parámetros para el texto
    myText <- "some Text"
    posCoordsVec <- c(0.5, 0.5)
    cex <- 2
    
    # Rectángulo
    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)
    
    # Ubicación del texto
    text(posCoordsVec[1], posCoordsVec[2], myText, cex = cex)
    

    Solución

    • Base graphics
    • Empleamos la función legend, con el mismo color en los bordes y relleno que en la solución inicial, y ajustamos el texto en el interior con el argumento 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
    • Con ggplot2 usamos la función geom_label. A diferencia de legend en base graphcis, el texto se centra automáticamente dentro del cuadro, con label.size = NA eliminamos los bordes

      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)
      

    Referencias

    2015-11-18

    Ajustar el espacio entre el gráfico y la leyenda en ggplot2

    Title

    Problema

    Queremos aumentar la distancia de separación entre el gráfico y la legenda usando el paquete ggplot2.

    library(ggplot2)
    xy <- data.frame(x = 1:10, y = 10:1, type = rep(LETTERS[1:2], each=5))
    plot <- ggplot(data = xy) +
            geom_point(aes(x = x, y = y, colo r= type))
    

    Solución

    plot <- plot + theme(legend.box.margin = margin(0, 0, 0, 20))
    

    Referencias

    Nube de datos