Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2 proportional squares

I am looking to make some kind of proportional squares (by lack of a better name) visualization in R. Example:

Billion Dollar O-gram

Any advice on how to do this in R (preferably ggplot2)?

like image 680
P.A. van der Laken Avatar asked Aug 10 '17 11:08

P.A. van der Laken


1 Answers

This type of visualization is called a treemap. Appropriately, you can use the treemap package. You can find a detailed tutorial for treemap here but I'll show you the basics. Below I show you how to create a treemap in ggplot2 as well.

Treemap package

library(treemap)

cars <- mtcars
cars$carname <- rownames(cars)

treemap(
  cars,
  index = "carname",
  vSize = "disp",
  vColor = "cyl",
  type = "value",
  format.legend = list(scientific = FALSE, big.mark = " ")
)

The output of the treemap function

ggplot2

There's also a developmental package on github for creating treemaps using ggplot2. Here's the repo for installing the package.

library(tidyverse)
library("ggfittext")
library("treemapify")

cars <- mtcars
cars$carname <- rownames(cars)
cars <- mutate(cars, cyl = factor(cyl))

ggplot(cars, aes(area = disp, fill = cyl, label = carname)) +
  geom_treemap() +
  geom_treemap_text(
    fontface = "italic",
    colour = "white",
    place = "centre",
    grow = TRUE
  )

enter image description here

like image 120
Andrew Brēza Avatar answered Sep 27 '22 23:09

Andrew Brēza