Our youtube channel

Our youtube channel has lots of videos on data visualisation in r.

Visit our youtube channel https://www.youtube.com/c/TechAnswers88

##Video link for heatmap charts https://youtu.be/27iBu77dUzY

Heatmap

We will use heatmap to compare two categorical variable combinations

Packages used

library(dplyr)
library(ggplot2)
library(viridis)

Prepare the data

If you prefer to use the SQL commands then you can use the sqldf package. See the instructions below. Here is a youtube video which talks about using sqldf in detail.
https://youtu.be/habwU-E6hBw



#ggplot2::diamonds
sml <- diamonds%>%
       dplyr::group_by(cut,color)%>%
       dplyr::tally()



# Those of you who like sql can use the following two commands to get the same results as above
#library(sqldf)
#sml <- sqldf("Select cut, color, count(*) as n from diamonds group by cut, color")
 

Create chart


pl <- ggplot(data = sml,aes( x = cut, y = color, fill=n))
pl <- pl + geom_tile()
pl

Customise the chart

Customise the chart with with title, subtitle, theme, labels, fill colour etc.

pl <- ggplot(data = sml,aes( x = cut, y = color, fill=n))
pl <- pl + geom_tile()
pl <- pl + theme_minimal()
pl <- pl + scale_fill_gradient(low="white", high="blue")
pl <- pl + labs(title = "Heatmap")
pl <- pl + labs(x ="Cut of diamonds", y ="Colour of diamonds")
pl <- pl + labs(subtitle = "Cut and color of diamonds")
pl <- pl + labs(caption =  paste0("n=", prettyNum(sum(sml$n), big.mark = ",")))
pl

Another chart using viridis package to change the fill colours.

# Another colour filling option using the viridis package

pl <- ggplot(data = sml,aes( x = cut, y = color, fill=n))
pl <- pl + geom_tile()
pl <- pl + theme_minimal()
pl <- pl + scale_fill_viridis(discrete=FALSE)
pl <- pl + labs(title = "Heatmap")
pl <- pl + labs(x ="Cut of diamonds", y ="Colour of diamonds")
pl <- pl + theme_minimal()
pl <- pl + labs(subtitle = "Cut and color of diamonds")
pl <- pl + labs(caption =  paste0("n=", prettyNum(sum(sml$n), big.mark = ",")))
pl

Our youtube channel

Our youtube channel has lots of videos on data visualisation in r.

Visit our youtube channel https://www.youtube.com/c/TechAnswers88