Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Know your data
Visualize your data – categorical variables
Work with your chart 2
14. Explain the legend, explain the chart
Check yourself 2

Instruction

Make sure that your legend title properly describes the variable.

A mosaic plot's legend tells the readers what is being correlated with the information on the horizontal axis. In this case, it is the countries' wealth categories.

The legend title is as important as an axis title or the chart title. It should be meaningful, but brief.

R will automatically generate a legend title for you. Ours is the exact name of variable. We can do better than that. We'll create a better title by adding the labs(fill = "your title") command to the chart. It adds a title to the scale used earlier. (Remember to enclose your title in double quotes.) Note: We used a scale to fill the rectangles, so the scale is called fill.

You should also order your legend in the same way as the colors appear on your chart. Our chart colors go from light on the bottom to dark on the top, so our legend should have the dark color on the top and the lightest color on the bottom.

To do this, we add:

+ guides(fill = guide_legend(reverse = TRUE))

This will reverse the current color order of the legend, giving us the results we want.

Exercise

Change the legend title and order as shown above. For example, you could use the title "level of alcohol consumption". In R code, it would look like this:

level of alcohol\nconsumption

The \n creates a line break, so consumption will be on its own line.

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

Stuck? Here's a hint!

You should write:

labs(fill = "level of alcohol\nconsumption") + 
guides(fill = guide_legend(reverse = TRUE))