Change Color of Range in ggplot2 Heatmap in R
A heatmap depicts the relationship between two attributes of a dataframe as a color-coded tile. A heatmap produces a grid with multiple attributes of the dataframe, representing the relationship between the two attributes taken at a time.
Dataset in use: bestsellers
Let us first create a regular heatmap with colors provided by default. We will use geom_tile() function of ggplot2 library. It is essentially used to create heatmaps.
- x: position on x-axis
- y: position on y-axis
- fill: numeric values that will be translated to colors
To this function, Var1 and Var2 of the melted dataframe are passed to x and y respectively. These represent the relationship between attributes taken two at a time. To fill parameters provide, since that will be used to color-code the tiles based on some numeric value.
Method 1: Using scale_fill_gradient()
In this method, the starting and the ending value of the colors to define a range is given as an argument.
Syntax: scale_fill_gradient(low, high, guide)
- low: starting value
- high: ending value
- guide: type of legend
Method 2: Using scale_fill_manual()
Up until now, we were adding colors to the continuous values, in this method, the values are first converted into discrete ranges using cut() function.
Syntax: cut(data, breaks)
Where breaks take a vector with values to divide the data by. Now again plot a heatmap but with the new data created after making it discrete. To add colors to such heatmap in ranges, use scale_fill_manual() with a vector of the colors for each range.
Syntax: scale_fill_manual(interval, values=vector of colors)