3

When I have multiple categorical variables in the x axis of a spineplot (base R graphics), I often find that some of my labels are missing. Is there a way to make the x axis labels vertical? Or better yet, is there an easy way to make spineplots using ggplot. I know I can do variable width stacked barcharts but they seem to be a pain to make these and even more of a pain to get the variable width bars close together. Although spineplots are nice and easy, I'd like to have more control in how they look.

Reproducible example:

spineplot(factor(mpg$drv)~factor(mpg$manufacturer), 
          xlab = "Manufacturer", ylab = "Wheel Drive")

#mpg comes from library(ggplot2)

Here I have 15 manufacturers but ten labels. I'd also like to have some color. spineplot r I have found these posts, but I do not find the solutions to be particularly easy

How to make variable bar widths in ggplot2 not overlap or gap

Variable Width Bar Plot

Community
  • 1
  • 1
yake84
  • 3,004
  • 2
  • 19
  • 35

1 Answers1

4

This takes some manipulation, based partly on this answer, for computing the necessary widths and positions of each bar. I chose to do the manipulation using dplyr, at which point you can create the desired spinegram:

library(dplyr)
d <- mpg %>%
    count(manufacturer, drv) %>%
    mutate(total = sum(n), fraction = n / total)

lab <- d %>%
    distinct(manufacturer) %>%
    select(manufacturer, total) %>%
    ungroup() %>%
    mutate(position = .5 * (cumsum(total) + cumsum(lag(total, default = 0))))

d %>%
    inner_join(lab) %>%
    ggplot(aes(position, fraction, fill = drv, width = total)) +
    geom_bar(stat = "identity") +
    scale_x_continuous(labels = lab$manufacturer, breaks = lab$position) +
    theme(axis.text.x = element_text(angle = 90, hjust = 1)) +
    xlab("Manufacturer")

ggplot2 spineplot

Community
  • 1
  • 1
David Robinson
  • 77,383
  • 16
  • 167
  • 187