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