GGPlot Gradient Color



GGPlot Gradient Color

This article describes how create a ggplot with gradient color. You will learn how to change the ggplot2 default gradient color, as well as, how to set gradient between two or n colors.



Contents:

Loading ggplot2

The following R code loads the ggplot2 R package and set the default plot theme to theme_minimal().

library(ggplot2)
theme_set(theme_minimal())

Default ggplot gradient colors

For gradient colors, you should map the map the argument color and/or fill to a continuous variable. The default ggplot2 setting for gradient colors is a continuous blue color.

In the following example, we color points according to the variable: Sepal.Length.

sp <- ggplot(iris, aes(Sepal.Length, Sepal.Width))+
  geom_point(aes(color = Sepal.Length))
sp

Key functions to change gradient colors

The default gradient colors can be modified using the following ggplot2 functions:

  • scale_color_gradient(), scale_fill_gradient() for sequential gradients between two colors
  • scale_color_gradient2(), scale_fill_gradient2() for diverging gradients
  • scale_color_gradientn(), scale_fill_gradientn() for gradient between n colors

Set gradient between two colors

Change the colors for low and high ends of the gradient:

# Sequential color scheme. 
# Specify the colors for low and high ends of gradient
sp + scale_color_gradient(low = "blue", high = "red")

# Diverging color scheme
# Specify also the colour for mid point
mid <- mean(iris$Sepal.Length)
sp + scale_color_gradient2(midpoint = mid, low = "blue", mid = "white",
                            high = "red", space = "Lab" )

Note that, the functions scale_color_continuous() and scale_fill_continuous() can be also used to set gradient colors.

Set gradient between n colors

In the example below, we’ll use the R base function rainbow() to generate a vector of 5 colors, which will be used to set the gradient colors.

sp + scale_color_gradientn(colours = rainbow(5))

Conclusion

This tutorial shows how to set gradient colors in ggplot2.



Version: Français





No Comments

Give a comment

Want to post an issue with R? If yes, please make sure you have read this: How to Include Reproducible R Script Examples in Datanovia Comments