Bar mekko graphics in R

This is a quick introduction to the bar mekko function* in the mekko package.

Its main value is to add quantitative context to a bar graph, via bar width.

knitr::opts_chunk$set(
  fig.width = 7,
  fig.height = 4
)


Install with:

install.packages("mekko")

You can also install the development version with devtools::install_github('ryninho/mekko', build_vignettes = TRUE).

View examples with:

vignette("mekko-vignette")

First we'll load ggplot and mekko and create some example data.

library(ggplot2)
library(mekko)
profits <- data.frame(
  product = c('widgets', 'sprockets', 'whosits', 'cogs', 'whatsits'),
  profit_margin = c(3.2, -1.4, -5.5, 0.5, 9.4),
  revenue = c(1150, 1900, 250, 700, 75)
  )

Bar mekko

Now let's take a look at profit margin by product using ggplot2.

ggplot(profits, aes(x = product, y = profit_margin, fill = product)) +
  geom_bar(stat = "identity")

Well that's insightful, but I don't know how worried I should be about the margin on whosits or cogs, nor do I know how happy I should be about whatsits knocking it out of the park. Maybe I can add revenue as the bar width so I know what's important here?

ggplot(profits, aes(x = product, y = profit_margin, width = revenue, position = "stack", fill = product)) +
  geom_bar(stat = "identity")

Well shucks, that looks like some kind of Atari graphics airplane. Let's use the mekko package to put our margins in context.

bmx <- barmekko(profits, product, profit_margin, revenue)
bmx

Alright, so actually the weak profit margins on sprockets may be worth nearly as much focus as the problem with whosits. Also, no high-fives for margins on the whatsits until we triple sales of them.

Those labels are a little close together- this is a ggplot object so let's use the usual method of rotating the axes.

bmx + theme(axis.text.x = element_text(angle = 90, hjust = 1))

When sorting by the width variable it usually pushes noise to one end

state.x77 %>% 
  data.frame %>% 
  rownames_to_column("State") %>% 
  arrange(Population) %>% 
  barmekko(State, Murder, Population) + 
  coord_flip() + 
  theme(legend.position="none") + 
  ggtitle("Murder Rate by State", 
  subtitle = "1977 Census (R dataset)") + 
  theme(axis.text.x = element_text(
    size = rel(1.5))
  )

Here we see how it can give us a sense of the weighted distribution of something

state.x77 %>% 
  data.frame %>% 
  rownames_to_column("State") %>% 
  arrange(Murder) %>% 
  barmekko(State, Murder, Population) + 
  coord_flip() + 
  theme(legend.position="none") + 
  ggtitle("Murder Rate by State", 
  subtitle = "1977 Census (R dataset)") + 
  theme(axis.text.x = element_text(
    size = rel(1.5))
  )

Appendix



ryninho/mekko documentation built on May 28, 2019, 10:45 a.m.