   Next: Statistics Up: R-tutorial Previous: Functions

# Plot

Flexible graphics capability is the strengths of R.
• A histogram can be made by typing:
```   > x <- rnorm(1000)
> hist(x)
```

• Scatter plot can be made by
```> x <- 0:10
> y <- log(x)
> plot(x,y)
```

You can add a straight line of y = a + b x by abline(a, b).

```> abline(0.5, 0.2)    # y-intercept = 0.5,  slope = 0.2
```

You can add more points by:

```> points (x, x * 0.2, pch=4)  # pch is points "character", i.e., symbol to use
```

You can connect the points by lines:

```> lines (x, y)
> lines (x, x * 0.2, lty = 2) # lty is line type
```

You can see the pre-set points characters:

```> example(points)
```

• To save this plot to a postscript file called, graph1.ps, type
```> dev.print(postscript,file="graph1.ps")
> dev.print(pdf,file="graph1.pdf")   # to make pdf
```

The file, graph1.ps, is saved in the directory in which R is invoked. Other graphical devices (i.e. pdf, jpeg, xfig, etc.) can be specified. To see other graphical devices, see `help(Devices)`.

• A matrix of scatterplots

`pairs(X)` produces a pairwise scatterplot matrix of the variables defined by the columns of X. Every column of X is plotted against every other column of X.

```> iris[1:5,]   # Anderson's iris data set
> pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species",
+       pch = 21, bg = c("red", "green3", "blue")[unclass(iris\$Species)])
> help(iris)
> help(pairs)  # Try the examples.
```
• multiple plots per page
```> par(mfrow = c(2,2))
> for (i in 1:4) { hist(iris[,i], xlab=names(iris)[i], main=i)}
> par(mfrow=c(1,1))     # setting the parameter back to the default
```
`par(mfcol=c(2,2))` is similar, but figures are filled by column.

• Bar plots:
```> VADeaths                        # death rates per 1000 in Virginian in 1940
> tVADeaths <- t(VADeaths)[,5:1]  # transpose, and change order of columns
> mp <- barplot(tVADeaths, beside=T, legend=colnames(VADeaths), ylim=c(0,130))
> fakeSE <- 2 * sqrt (1000 * tVADeaths/100)  # making a fake error bar
> mp                              # contains x-coordinates
> segments (mp, tVADeaths, mp, tVADeaths+fakeSE, lwd=1.5)
```
You can easily make a customized ``wrapper'' function to do all of this if you repeatedly use the same plotting procedure.

• Advanced graphics:
See R Graph Gallery for more advanced graphics. The web page contains the example codes to produce the fancy figures, so you can learn through immitation.   Next: Statistics Up: R-tutorial Previous: Functions
Naoki Takebayashi 2009-03-27