Given a numerical matrix you will need to transform it into a data frame that ggplot2 can understand. For that purpose you can use the melt
function from reshape
package.
geom_tile
A heap map in ggplot2 can be created with geom_tile
, passing the categorical variables to x
and y
arguments and the continuous variable to fill
argument of aes
.
Square tiles
Note that depending on the plotting windows size the tiles might not be squared. If you want to keep them squared use cood_fixed
.
Border customization
You can customize the border color, line width and line style of the tiles with color
, lwd
and linetype
, respectively.
Adding the values
In addition, you can add the values over the tiles with geom_text
, passing the numerical variable to the label
argument of the aes
function.
There three ways to change the default color palette used when creating the heat map: using scale_fill_gradient
, scale_fill_gradient2
or scale_fill_gradientn
.
scale_fill_gradient
This function allows changing the colors, setting a lower and a higher color to represent the values of the heat map.
scale_fill_gradient2
If you want to add a mid color you can use scale_fill_gradient2
, which includes the mid
argument.
scale_fill_gradientn
Finally, you can also use a custom color palette with scale_fill_gradientn
, which allows passing n colors to the colors
argument. In this example we are passing 20 colors of the "RdYlGn"
palette.
Width and height
You can change the width and the height of the legend color bar with the following code:
Change the title
The default title of the legend is the name of the continuous variable of the data frame. If you want to change it pass a string to the title
argument of the guide_colourbar
function.
Remove the labels and the ticks
You can also remove the labels and/or the ticks of the legend, setting the corresponding arguments to FALSE
.
Remove the legend
Finally, it you want to get rid of the legend you can set its position to "none"
.
See also