Scatter with multiple group

Most of the time it becomes essential to have a plot with multiple categories, i.e. colour coding scatter plot according to gender or have two different regression line for each of them.

Lets scatter the same points that the post – has dealt with but this time the points are coloured according to Transmission system (automatic vs manual) of the cars. In this article, the same three packages – Base Graphics, Lattice Plot and ggPlot will be used.

Using R Base Graphics

Plot of Mile per gallon vs Displacement

BaseGraphics

Source Code

Using Lattice Graphics

The Plot

In this section Lattice and Lattice Extra packages should be installed using the command
install.packages("lattice")and
install.packages("latticeExtra"). Then the package should be loaded using
library()

LatticeGraphics

Source Code

To install lattice and latticeExtra package, you can use install.packages() function. It should be loaded after installation with library() function.

Using ggPlot2

The Plot

Creating a ggPlot graphics is possible with installation of ggplot2 package. This package can create beautiful and sophisticated plots with simple syntax.

ggPlot

Source Code

Installation of ggplot2 package,

The linear model and the fitted function

Call:
lm(formula = mpg ~ disp + am, data = mtcars)

Residuals:
Min 1Q Median 3Q Max
-4.6382 -2.4751 -0.5631 2.2333 6.8386

Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 27.848081 1.834071 15.184 2.45e-15 ***
disp -0.036851 0.005782 -6.373 5.75e-07 ***
am1 1.833458 1.436100 1.277 0.212
---
Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1

Residual standard error: 3.218 on 29 degrees of freedom
Multiple R-squared: 0.7333, Adjusted R-squared: 0.7149
F-statistic: 39.87 on 2 and 29 DF, p-value: 4.749e-09

For Automatic Transmission:

$$\texttt{mpg}=27.85-0.04\texttt{disp}$$

For Manual Transmission:

$$\texttt{mpg}=27.85-(0.04+1.83)\texttt{disp} = 27.85-1.87\texttt{disp}$$