1

In a mosaicplot, how do I relabel the bins?

dat <- data.frame(letters = sample(LETTERS[1:3], 15, replace = TRUE),
                  numbers = sample(3, 15, replace = TRUE))
mosaicplot(table(dat))

That is, how can I change the "A", "B", and "C" in the plot below to, say, "dogs", "cows", and "chicken"?

enter image description here

user20650
  • 24,654
  • 5
  • 56
  • 91

2 Answers2

3

One way is to rename the table dims...

dat <- data.frame(letters = sample(LETTERS[1:3], 15, replace = TRUE),
                  numbers = sample(3, 15, replace = TRUE))

tab1 <- table(dat)
dimnames(tab1)[[1]] <- c("dogs","cows","chicken")
## note that dimnames(tab1)$letters <- c("dogs","cows","chicken") will work equally well

mosaicplot(tab1)
Matt Tyers
  • 2,125
  • 1
  • 14
  • 23
  • Thank you. Is there a way to do it without creating extra objects? That is, can the labels be added as an argument to either `table()` or `mosaicplot()`? –  Jun 19 '17 at 19:11
1

As an addition to @MattTyers solution and a follow-up to the question whether everything can be done in one go: You can use the formula method for mosaicplot() and employ factor() inside the formula to assign new labels to the levels of the factor. Note that you need to set xlab and ylab explicitly in order not to have labels like factor(..., labels = ...).

mosaicplot(~ factor(letters, labels = c("Aah", "Bee", "Cea")) +
  factor(numbers, labels = c("one", "two", "three")),
  data = dat, xlab = "Letters", ylab = "Numbers")
Achim Zeileis
  • 15,710
  • 1
  • 39
  • 49