# R Programming/Graphics

R Programming
* R Basics
** Introduction
** Sample Session
** Manage your workspace
** Settings and Installation
** Documentation
** Control Structures
** Working with functions
** Debugging
** Using C or Fortran
** Utilities
** Estimation utilities
** Packages
* Data Management
** Data types
** Working with data frames
** Importing and exporting data
** Text Processing
** Times and Dates
* Graphics
** Grammar of graphics
* Publication quality output
* Descriptive Statistics
* Mathematics
** Optimization
** Probability Distributions
** Random Number Generation
* Statistical Core Methods
** Maximum Likelihood
** Method of Moments
** Bayesian Methods
** Bootstrap
** Multiple Imputation
** Nonparametric Methods
* Regression Models
** Linear Models
** Quantile Regression
** Binomial Models
** Multinomial Models
** Tobit And Selection Models
** Count Data Models
** Duration Analysis
* Time Series
* Factor Analysis
* Classification
** Ordination
** Clustering
* Network Analysis
* High Performance Computing
** Profiling R code
** Parallel computing with R
* Appendix
** Sources
** Index
R includes at least three graphical systems, the standard graphics package, the lattice package for Trellis graphs and the grammar-of-graphics ggplot2 package. R has good graphical capabilities but there are some alternatives like gnuplot.

## Interactive Graphics

This section discuss some ways to draw graphics without using R scripts.
The playwith package provides a graphical user interface to customize the graphs, add a title, a grid, some text, etc and it exports the R code you need if you want to replicate the analysis. If you want to know more, you can have a look at the screenshots on the website (link). See also the example on "R you Ready" . This package require GTK+ libraries.
There is also a graphical user interface GrapheR which makes it very easy to draw graphs for beginners. This solution is cross-platform.
latticist (link) is another similar project.
Note also that some graphical user interface such as RKward and R Commander makes it easy to draw graphs.

## Standard R graphs

In this section we present what you need to know if you want to customize your graphs in the default graph system.
* plot is the main function for graphics. The arguments can be a single point such as 0 or c(.3,.7), a single vector, a pair of vectors or many other R objects.
* par is another important function which defines the default settings for plots.
* There are many other plot functions which are specific to some tasks such as hist, boxplot, etc. Most of them take the same arguments as the plot function.

### Titles, legends and annotations
#### Titles

main gives the main title, sub the subtitle. They can be passed as argument of the plot function or using the title function. xlab the name of the x axis and ylab the name of the y axis.
The size of the text can be modified using the parameters cex.main, cex.lab, cex.sub, cex.axis. Those parameters define a scaling factor, ie the value of the parameter multiply the size of the text. If you choose cex.main=2 the main title will be twice as big as usual.

#### Legend

legend. The position can be "bottomleft", "bottomright", "topleft", "topright" or exact coordinates.

#### Text in the margin

mtext puts some texts in the margin. The margin can be at the bottom (1), the left (2), the top (3) or the right (4).

#### Text in the graph

text

#### Mathematical annotations

We can add mathematical symbols using expression and makes some substitution in a formula using substitute.

### Types

The type of a plot can be :
* n for none (nothing is printed),
* p for points,
* l for lines,
* b for both,
* o for both overlayed,
* h for histogram-like
* and s/S for steps.
| R code | Output |
| x1 <- rnorm(50) png("plottype.png") par(mfrow = c(2,2)) plot(x1, type = "p", main = "points", ylab = "", xlab = "") plot(x1, type = "l", main = "lines", ylab = "", xlab = "") plot(x1, type = "b", main = "both", ylab = "", xlab = "") plot(x1, type = "o", main = "both overplot", ylab = "", xlab = "") dev.off | click on the graph to zoom |

### Axes

The default output print the axes. We can remove them with axes=FALSE. We can also change them using the axis function.
las specifies the style of axis labels. It can be 0, 1, 2 or 3.
* 0 : always parallel to the axis [default],
* 1 : always horizontal,
* 2 : always perpendicular to the axis,
* 3 : always vertical.
| R code | Output |
| x1 <- rnorm(100) par(mfrow = c(2,2)) plot(x1, las = 0, main = "las = 0", sub = "always parallel to the axis", xlab = "", ylab = "") plot(x1, las = 1, main = "las = 1", sub = "always horizontal", xlab = "", ylab = "") plot(x1, las = 2, main = "las = 2", sub = "always perpendicular to the axis", xlab = "", ylab = "") plot(x1, las = 3, main = "las = 3", sub = "always vertical", xlab = "", ylab = "") | click on the graph |
It is also possible to add another y axis on the right by adding axis(4,).

### Margins

Margins can be computed in inches or in lines. The default is par(mar = c(5,4,4,2)) which means that there are 5 lines at the bottom, 4 lines on the left, 4 lines in the top and 2 lines on the right. This can be modified using the par function. If you want to specify margins in inches, use par(mai = c(bottom, left, top, right). If you want to modify margins in lines, use par(mar = c(bottom, left, top, right). See ?par to learn more about the topic.

### Colors

The color of the points or lines can be changed using the col argument, fg for foreground colors (boxes and axes) and bg for background colors.
* show.col(object=NULL) (Hmisc) package plots the main R colors with their numeric code.
* The list of all colors in R (pdf)
* We can also generate new colors using the rgb function. The first argument is the intensity of red, the second, the intensity of green and the third, the intensity of blue. They vary between 0 and 1 by default but this can be modified with the option max = 255. col2rgb returns the RGB code of R colors. col2hex (gplots) gives the hexadecimal code. col2grey and col2gray (TeachingDemos) converts colors to grey scale.

### Points

For points the symbols can be changed using the pch option which takes integer values between 0 and 25 or a single character. pch can also takes a vector as argument. In that case the first points will use the first element of the vector as symbol, and so on.
The following code displays all the symbols on the same plot :
points adds points to an existing plot.

### Lines

We can change the line type with lty. The argument is a string ("blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash") or an integer (0=blank, 1=solid (default), 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash). The line width can be changed with lwd. The default is lwd=1. lwd=2 means that the width is twice the normal width.
lines adds an additional lines on a graph.
abline adds an horizontal line (h=), a vertical line (v=) or a linear function to the current plot (a= for the constant and b= for the slope). abline can also plot the regression line.

### Boxes

Each graph is framed by a box. bty specifies the box type.
See also box to add a box to an existing plot.

### Grid

grid adds a grid to the current graph.
Although grid has an optional argument nx for setting the number of grid lines, it is not possible to tell it explicitly where to place those lines (it will usually not place them at integer values). A more precise and manageable alternative is to use abline.

### Other figures

We can also add a circle to a plot with the circle function in the calibrate package.

### Background

You can choose the background of your plot. For instance, you can change the background color with par(bg=).

### Overlaying plots

matplot can plot several plots at the same time.

### Multiple plots

With par we can display multiple figures on the same plot. mfrow = c(3,2) prints 6 figures on the same plot with 3 rows and 2 columns. mfcol = c(3,2) does the same but the order is not the same.

### Plotting a function

* curve plots a function. This can be added to an existing plot with the option add = TRUE.
* plot can also plots functions.
* square root function, made using plot

## Exporting graphs

How can you export a graph ?
* First you can plot the graph and use the context menu (right click on Windows and Linux or control + click on Mac) to copy or save the graphs. The available options depend on your operating system. On Windows, you can also use copy the current graph to the clipboard as a Bitmap file (raster graphics) using CTRL + C or as a Windows Metafile (vector graphics) using CTRL + W. You can then paste it into another application.
* You can export a plot to pdf, png, jpeg, bmp or tiff by adding pdf("filename.pdf"), png("filename.png"), jpeg("filename.jpg"), bmp("filename.bmp") or tiff("filename.tiff") prior to the plotting, and dev.off after the plotting.
* You can also use the savePlot function to save existing graphs.
* Sweave also produce ps and pdf graphics (See the Sweave section).
It is better to use vectorial devices such as pdf, ps or svg.
How can you know the list of all available devices ?
* ?Devices
* Use the capabilities function to see the list of available devices on your computer.
We can also export to SVG using the svg function.
The RSvgDevice library which was used in earlier versions of R seems now outdated.

## Advanced topics
### Animated plots

The animation package provides dynamic graphics capabilities. It is possible to export the animation in flash, mpeg or gif format. There are more example on the aniwiki website : http://animation.yihui.name/.
You can also create motion charts using the googleVis package.

#### Examples
### Interactive Graphics

The iplots package provides a way to have interactive data visualization in R ·.
* R GUI now offers interactive graphics – Deducer 0.4-2 connects with iplots
To create an interactive, animated plot viewable in a web browser, the animint package can be used. The main idea is to define an interactive animation as a list of ggplots with two new aesthetics:
* showSelected=variable means that only the subset of the data that corresponds to the selected value of variable will be shown.
* clickSelects=variable means that clicking a plot element will change the currently selected value of variable.

## Graphics gallery

In this section, we review all kind of statistical plots and review all alternatives to draw them using R. This include code for the standard graphics package, the lattice package and the ggplot2 package. Also, we add some examples from the commons repository. We only add examples which are provided with the R code. You can click on any graph and find the R code.

### Line plot

To draw a line plot, use the generic plot function by setting type="l".
Then, you can add further lines on the same plot using the lines function.

#### Examples
### Scatter plot

* plot(x,y)
* plot(y ~ x)
* xyplot(y ~ x) (lattice)
* qplot(x,y) (ggplot2)

#### Log scale

Sometimes it is useful to plot the log of a variable and to have a log scale on the axis. It is possible to plot the log of a variable using the log option in the plot function.
* For a log log plot, use log = "xy"
* For a log in the x axis only, use log = "x"
* For a log in the x axis only, use log = "y"

#### Label points in a plot

* It is possible to add labels with the text function.
* textxy (calibrate) makes it easy to add labels.

#### Examples
### Histogram

* hist
* histogram (lattice)
You can learn more about histograms in the Non parametric methods page.

#### Examples
### Box plot

Box plot :
* boxplot

#### See also

* How to label all the outliers in a boxplot

### Bar charts

See Bar charts on wikipedia.
* barplot takes a table as argument and returns a bar chart.
* qlot (ggplot2) with the option geom = "bar" takes a variable as argument and returns a bar chart.
* barchart takes a variable as argument and returns a bar chart.

#### Examples
### Dot plot

See also Dot plot on Wikipedia.
* dotchart

#### Examples
### Pie charts

* pie

#### Examples
### Treemap

The tmPlot function in the treemap package makes it easy to draw a treemap.

### Confidence interval plot

Standard error bar chart are very useful to plot several estimates with confidence intervals.
* The Hmisc package has an errbar function. This function takes the upper and lower bounds of the confidence intervals as argument.
* coefplot function in Gelman and Hill's arm package. This functions is designed to display estimation results. It takes point estimates and standard errors as arguments.
See also
* There is another errbar function in the sfsmisc package.
* plotCI (gplots) also plot error bars.
* plotmeans (gplots)
* ciplot (hacks)
* See also Error bar on Wikipedia

### 3D plots

* contour, image, persp
* plot3d (rgl)
* wireframe (lattice)

#### Examples

* click on the graph to see the R code
* Example with wireframe (lattice)

### Diagrams

* grid package by Paul Murrell
* diagram package
* Rgraphviz package
* igraph package

### Arc Diagrams

It is also possible to draw Arc Diagrams.

### Dendrograms

It is possible to plot dendrograms in R.

### Treemap

It is possible to draw a treemap using the treemap function in the treemap package.

### Wordcloud

There is :
* the wordcloud function in the wordcloud package
* the tagcloud function in the tagcloud package

### Timeline

* timeline in the timeline package

### Maps
#### See also

* Geograpic Maps in R (Revolution Computing Blog)
* Global Administrative Areas
* Andy Egger's googlemap.r function

## Resources

* Tables 2 Graphs
* R Graphics by Paul Murrell
* ggplot2
* Graphical Parameters

## References

* ↑ D. Sarkar. Lattice: Multivariate Data Visualization with R. Springer, 2008. ISBN 9780387759685.
* ↑ ggplot2: Elegant Graphics for Data Analysis (Use R) by Hadley Wickham and a list of examples on his own website : http://had.co.nz/ggplot2/
* ↑ playwith : http://code.google.com/p/playwith/
* ↑ Hervé, Maxime (2011). "GrapheR: a Multiplatform GUI for Drawing Customizable Graphs in R" (PDF). The R Journal. 3 (2).
* ↑ Tutorial for the googleVis package : http://stackoverflow.com/questions/4646779/embedding-googlevis-charts-into-a-web-site/4649753#4649753
* ↑ http://www.r-bloggers.com/interactive-graphics-with-the-iplots-package-from-%E2%80%9Cr-in-action%E2%80%9D/
* ↑ http://www.r-statistics.com/2012/01/interactive-graphics-with-the-iplots-package-from-r-in-action/ Interactive Graphics with the iplots Package] - a chapter from the R in action book
* ↑ Hadley Wickham ggplot2: Elegant Graphics for Data Analysis, Springer Verlag, 2009
* ↑ The default output in errbar changed between R version 2.8.1 and R version 2.9.2. Axis are not displayed by default anymore
* ↑ Paul Murrell Drawing Diagrams with R, The R Journal, 2009 http://journal.r-project.org/2009-1/RJournal_2009-1_Murrell.pdf
* ↑ (example: Using a binary tree diagram for describing a Bernoulli process)
* ↑ Gaston Sanchez (Feburary 3rd, 2013). "Arc Diagrams in R: Les Miserables". Retrieved February 5th, 2013. {{cite web}}: Check date values in: |accessdate= and |date= (help)
* ↑ Gaston Sanchez (October 3, 2012). "7+ ways to plot dendrograms in R". Retrieved February 5th, 2013. {{cite web}}: Check date values in: |accessdate= and |date= (help); line feed character in |date= at position 9 (help)
* ↑ http://cran.r-project.org/web/packages/treemap/treemap.pdf
* ↑ http://www.stat.auckland.ac.nz/~paul/RGraphics/rgraphics.html
* ↑ http://had.co.nz/ggplot2/