Friday 30 November 2018

Quick legends with chord plots

Quick legends with circlize chord plots
The circlize package from Zuguang Gu is fantastic for drawing chord plots, amongst other things. It will even allow multiple arrows between two nodes.
library(circlize)
#create quick dataframe
links <- expand.grid(c("From_A","From_B"), c("To_C","To_D", "To_E"), c("cars", "vans"))
names(links) <- c("from", "to", "type")
links$traffic <- sample.int(15, size = nrow(links))
#colours
links$colour <- ifelse(links$type == "cars", "red", "blue")
chordDiagram(links[,c("from", "to", "traffic")],
             col = links$colour,
             directional = 1, direction.type = "arrows", link.arr.type = "big.arrow")


The documentation is excellent. The catch in this case is that, if you want to add a legend, Gu refers you to yet another package ComplexHeatmap, which isn’t (currently?) available on CRAN, but via bioconductor. If, like me, you prefer not to have one package per line of code ;-) , all is not lost. There’s a quick way to get a legend, with base graphics, and another function already in circlize.
You need graphics::legend, plus circlize:add_transparency so that the colours in your legend match those used for the chords.

#for consistency
transparency <- 0.5
chordDiagram(links[,c("from", "to", "traffic")],
             col = links$colour,
             directional = 1, direction.type = "arrows", link.arr.type = "big.arrow",
             transparency = transparency)
legend(x = "bottomleft", inset = 0.05, bty = "n",
           legend = c("Cars", "Vans"),
           fill = add_transparency(c("red", "blue"), transparency),
           border = "white")

No comments:

Post a Comment