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

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

2016-01-09

Cómo añadir etiquetas a los extremos de una leyenda continua en ggplot2

Title

Problema

Queremos añadir etiquetas a los extremos de una legenda continua en ggplot2. Así podremos saber el mínimo y el máximo.

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

Se observa en la leyenda como las etiquetas van del 2.000 al 8.000 pero no sabemos ni el mínimo ni el máximo.

Solución

Dentro de scale_colour_gradient, especificamos los argumentos breaks y 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))

Ahora hemos añadido a la leyenda el mínimo 257 y el máximo 8.888.

Extra

Si queremos que en lugar de una escala de azules, parta de un color diferente, por ejemplo el rojo, añadimos el argumento low. Si queremos modificar el color superior introduciríamos el argumento 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")

Referencias

Entradas relacionadas

Nube de datos