Chapter 13. Miscellaneous Graphs

There are many, many ways of visualizing data, and sometimes things don’t fit into nice, tidy categories. This chapter shows how to make some of these other visualizations.

13.1 Making a Correlation Matrix

Problem

You want to make a graphical correlation matrix.

Solution

We’ll look at the mtcars data set:

mtcars
#>                mpg cyl disp  hp drat    wt  qsec vs am gear carb
#> Mazda RX4     21.0   6  160 110 3.90 2.620 16.46  0  1    4    4
#> Mazda RX4 Wag 21.0   6  160 110 3.90 2.875 17.02  0  1    4    4
#> Datsun 710    22.8   4  108  93 3.85 2.320 18.61  1  1    4    1
#>  ...<26 more rows>...
#> Ferrari Dino  19.7   6  145 175 3.62 2.770 15.50  0  1    5    6
#> Maserati Bora 15.0   8  301 335 3.54 3.570 14.60  0  1    5    8
#> Volvo 142E    21.4   4  121 109 4.11 2.780 18.60  1  1    4    2

First, generate the numerical correlation matrix using cor. This will generate correlation coefficients for each pair of columns:

mcor <- cor(mtcars)
# Print mcor and round to 2 digits
round(mcor, digits = 2)
#>        mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
#> mpg   1.00 -0.85 -0.85 -0.78  0.68 -0.87  0.42  0.66  0.60  0.48 -0.55
#> cyl  -0.85  1.00  0.90  0.83 -0.70  0.78 -0.59 -0.81 -0.52 -0.49  0.53
#> disp -0.85  0.90  1.00  0.79 -0.71  0.89 -0.43 -0.71 -0.59 -0.56  0.39
#>  ...<5 more rows>...
#> am    0.60 -0.52 -0.59 -0.24  0.71 -0.69 -0.23  0.17  1.00  0.79  0.06
#> gear  0.48 -0.49 -0.56 -0.13  0.70 -0.58 -0.21  0.21  0.79  1.00  0.27
#> carb -0.55  0.53  0.39  0.75 -0.09  0.43 -0.66 -0.57  0.06  0.27  1.00

If there are any columns that you don’t want used for correlations ...

Get R Graphics Cookbook, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.