Know your data
Visualize your data – categorical variables
10. Draw the mosaic chart 2
Work with your chart 2
Check yourself 2

Instruction

Now we can add the second variable to our plot. To do that, we will again use geom_mosaic:

ggplot(data = dataset) + geom_mosaic(aes(x = product(variable_y, variable_x), fill=variable_y))

Notice that variable_y is in two places: inside the product function (as part of the x argument) and in the fill argument. It is important to place variable_y first in the product function, before variable_x.

Exercise

Create the final version of our mosaic plot using the above syntax. Set alcohol_wealth2 as the dataset, consumption_cat as variable_y and wealth_index_cat as variable_x.

When you're done, press the Run and Check Code button.

Stuck? Here's a hint!

You should write

mosaicplot <- ggplot(data = alcohol_wealth2) +
 geom_mosaic(
   aes(x = product(consumption_cat, wealth_index_cat), 
   fill = consumption_cat))