R Graphs - gizotso/R GitHub Wiki
Graphs with R
Graph functions (default R packages graphics & stats)
-
plot(x),plot(x, y) -
matplot(x, y),matplot(M): bivariate plot. Plot columns of one matrix against columns of another. (x[,1] vs y[,1], x[,2] vs y[,2], ...) x,y: vector or matrices. -
sunflowerplot(x, y): plot(x, y) but overlapping (superimposed) points are shown as flowers with number of petals equal to number of overlapping pointss -
piechart() -
hist(x): histogram -
boxplot() -
barplot(x) -
mosaicplot(x): visualizing data from 2 or more qualitative variables example @statmethods.net -
dotchart(): dotplot example @statmethods.net -
stripchart(): 1-D scatter plot (or dot plot). Good alternative to boxplots when sample sizes are small example @programiz.com -
pairs(): scatterplot matrix (bivariate graphs)pairs(iris[1:4], main = "Anderson's Iris Data -- 3 species", pch = 21, bg = c("red", "green3", "blue")[unclass(iris$Species)])
-
coplot(x~y |z): Conditioning plots. Useful for visualizing interactions in the dataset. ex: how vary lat vs long given depth- coplot(lat ~ long | depth, data = quakes, columns=6)
- coplot(lat ~ long | depth * mag, data = quakes, number=c(3,4))
-
qqplot(x, y): Quantile-Quantile plotqqnorm(x): normal QQ plot. (x quantiles vs quantiles from a Normal distribution)
-
contour(x, y, z), filled.contour(x, y, z), image(x, y, z), persp(x, y, z) : 3-D surface representation. x,y vectors and z matrix : dim(z)=c(length(x), length(y)) -
interaction.plot(f1, f1, y): 2-way interaction plot. Plots the Mean (or other summary) of the response for two-way combinations of factors, thereby illustrating possible interactions. -
fourfoldplot(x): fourfold display of a 2 by 2 by k contingency table. Visual analysis with circle quarter of the association between two dichotomous variables in one or several populations. x array with dim=[2, 2, k] or matrix with dim = [2, 2] if k=1 -
assocplot(x): Association Plot (contingency table visualization). see alsoassoc()in vcd package.- ct <- margin.table(HairEyeColor, c(1, 2)) assocplot(ct, main = "Relation between hair and eye color")
-
plot.ts(x): Plotting time series objects -
ts.plot(x): Plot multiple time series (series can have a different time bases but should have same frequency)
Graph add-on functions (adds elements on current plot)
title(): adds a title / subtitlelegend(x, y, legend): adds legends to plots at location (x,y) with symbols given by legend (character or expression vector of length ≥ 1 to appear in the legend)box(): adds a box around the plotaxis(side, v): adds an axis (side= 1=> bottom, 2=>left, 3, top, 4=>right). Optional vector tickmark locations.rug(x): adds a rug representation (1-d plot, made of small vertical bars) of the data to the plot. Great in conjonction with jitter() to add some noise.ablineabline(a, b): line with slope b and intersect aabline(h=a): horizontal lineabline(v=a): vertical lineabline(lm.obj): adds linear regression line given by lm.obj
lines(x, y): adds connected line segments (x, y : coordinate vectors of points to join)polygon(x, y): adds a polygonrect(x1, y1, x2, y2): adds a rectanglesegments(x0, y0, x1, y1): adds line segments (x0,yo) -- (x1,y1)arrows(x0, y0, x1, y1, angle=30, code=2): segments with arrows in point (x0,yO) if code=2, in point (x1,y1) if code=3 or in both sides if code=3
points(x, y): adds points
plot(-4:4, -4:4, type = "n") # setting up coord. system
points(rnorm(200), rnorm(200), col = "red")
points(rnorm(100)/2, rnorm(100)/2, col = "blue", cex = 1.5)
-
text(x, y, labels, ...): draws the strings given in the vector labels at the coordinates given by x and y -
mtext(text, side=3, line=0): write text into the margin (side={1,2,3,4}) of a plot. -
locator(n, type="n", ...): Graphical input: Reads the position (x,y) of the graphics cursor and returns them when the mouse button has been pressedntimes. type {"n", "p", "l", "o"} "n" no plot, "p": plot points, "n" or "o" plot joined points with lines
text(x, y, expression(p == over(1, 1+e^-(beta*x+alpha))))
# R² = 0.986
text(x, y, as.expression(substitute(R^2==r, list(r=round(Rsquared, 3)))))
text(x, y, as.expression(substitute(italic(R)^2==r, list(r=round(Rsquared, 3)))))
Devices
- Devices
x11(),windows(): windowpdf("report.pdf"): pdf filepostscript("graph.ps"): postscript filebmp("image.bmp"),jpeg(),png(): images
dev.list(): liste les dispositifs ouvertsdev.cur(): dispositif courant. Cf help(dev.cur)dev.set(3): set le dispositif courantdev.off(): ferme le dispositif
x11(); pdf()
> dev.list()
windows pdf
2 3
Graph Layout : combining plots
R makes it easy to combine multiple plots into one overall graph, using either the layout( ) or par(mfrow=c() ) function.
layout(mat=, widths=, heights=, respect=FALSE|TRUE)
m <- matrix(c(1:3, 3), 2, 2)
> m
[,1] [,2]
[1,] 1 3
[2,] 2 3
layout(m)
layout.show(3)
4 plots
nf <- layout(matrix(1:4, 2, 2), widths=c(1, 3), heights=c(3, 1))
layout.show(nf)
Plot with marginal Plots
# 3 is the main plot
> matrix(0:3, 2, 2)
[,1] [,2]
[1,] 0 2
[2,] 1 3
# 1 is the main plot
> m = matrix(c(2,0,1,3),2,2,byrow = TRUE)
> m
[,1] [,2]
[1,] 2 0
[2,] 1 3
nf <- layout(m, c(3,1), c(1,3), TRUE)
# heigth and width ratios set, proportions are frozen
layout.show(nf)

Graphical Parameters
-
par: set or query graphical parameters. -
?par: help on graphical parameters -
adj: how text strings are justified in text(), mtext() and title(). 0=left, 0.5=center, 1=right -
bg: background color. ex bg="red". Usecolors()to list R colors. -
bty="n": {"o","1","7","u","]"} type of box drawn around plot. "n" suppresses the box. -
cex: num value (default 1) giving the amount by which plotting text and symbols should be magnified relative to the default- cex.axis (axis), cex.lab (axis annotations), cex.main (title), cex.sub (subtitle)
-
col: symbol color- col.axis, cold.lab, col.main, col.sub
-
font: 1=normal, 2=italic, 3=bold, 4=bold italic.- font.axis, font.lab, font.main, font.sub
-
las=0: {0,1,2,3} axis label style. 0=always parallel to the axis, 1=always horizontal, 2 = always perpendicular to the axis, 3=always vertical -
lty: Line type {0,1,2,3,4,5,6}: 0=blank, 1=solid (default), 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash or {blank", "solid", "dashed", "dotted", "dotdash", "longdash", or "twodash"} Alternatively a string of up to 8 characters may be given. ex: lty="44" would be similar to lty=2 -
lwd=1: Line width {positive number} -
mar: numerical vector of the form c(bottom, left, top, right) which gives the number of lines of margin to be specified on the four sides of the plot. The default isc(5.1, 4.1, 4.1, 2.1) -
mfcol,mfrow: vector of the form c(nr, nc). Subsequent figures will be drawn in an nr-by-nc matrix on the device by columns (mfcol), or rows (mfrow) -
pch: plotting symbol (0:25) or char ("*", "+") -
ps: {integer} point size of text (but not symbols) -
pty: type of plotting region to be used; "s"=square "m"=maximal -
tck=NA: length of tick marks as a fraction of the smaller between width and height of the plotting region. -
tcl=-0.5: length of axis tick marks as a fraction of the height of a line of text -
xaxt,yaxy: "n" suppresses axis plotting (axis is defined). useful with axis(side=1, ...) resp axis(side=2, ...)
Plot Symbols
- http://www.endmemo.com/program/R/pchsymbols.php pch = 1 :25
http://www.statmethods.net/advgraphs/parameters.html
Graphs examples
- http://en.wikibooks.org/wiki/R_Programming/Graphics
- http://rgraphgallery.blogspot.fr/
- http://www.cyclismo.org/tutorial/R/intermediatePlotting.html
- http://www.statmethods.net/advgraphs/probability.html
- Related to distribution plots : http://zoonek2.free.fr/UNIX/48_R/07.html
- http://shinyapps.org/apps/RGraphCompendium/index.php
- http://rgraphgallery.blogspot.fr/2013/04/rg-plotting-boxplot-and-histogram.html
- http://mazamascience.com/WorkingWithData/?p=958
- http://www.r-bloggers.com/ggextra-r-package-for-adding-marginal-histograms-to-ggplot2/
- http://www.statmethods.net/graphs/density.html
Colors
- http://research.stowers-institute.org/efg/R/Color/Chart/
- https://www.nceas.ucsb.edu/~frazier/RSpatialGuides/colorPaletteCheatsheet.pdf
R DataViz Packages
library(grid) library(help = "grid") library(lattice)
-
lattice
barchart(y ~ x): barchartbwplot(y ~ x): Comparative boxplot by xhistogram(~ x),densityplot(~ x)stripplot(y ~ x): 1-D plot of x (numeric), y can be a factor.xyplot(y ~ x): bivariate plots.dotplot(y ~ x): graphe de Cleveland (graphes superposés ligne par ligne et colonne par colonne)qqmath(~ x): QQ Plot with theoritical distribution. quantiles de x en fonction des valeurs attendues selon une distribution théoriqueqq(y ~ x): QQ Plot of 2 samples. x numeric, y categorical with at least 2 levels.
-
ggplot2
-
grid
levelplot(z ~ x*y): graphe en couleur des valeurs de z aux coordonnées fournies par x et y (x, y et z sont tous de même longueur)contourplot(z ~ x*y):cloud(z ~ x*y): graphe 3-D en perspective (points)wireframe(z ~ x*y): idem (surface)splom(~ x): matrice de graphes bivariésparallel(~ x): graphe de coordonnées parallèles
-
treemap
-
Rgraphviz
-
Diagram
-
Wordcloud, tagcloud
-
timeline
-
playwith : https://github.com/floybix/playwith
-
latticist : https://github.com/floybix/latticist
ggplot2
- http://www.r-bloggers.com/how-to-make-a-histogram-with-ggplot2/
- http://www.ling.upenn.edu/~joseff/rstudy/summer2010_ggplot2_intro.html
- http://www.cookbook-r.com/Graphs/Plotting_distributions_(ggplot2)/#histogram-and-density-plots
- https://github.com/kassambara/easyGgplot2
- http://www.r-bloggers.com/wanted-a-perfect-scatterplot-with-marginals/ --> Ggextra
- http://daattali.com/shiny/ggExtra-ggMarginal-demo/
mosaic package
- https://cran.r-project.org/web/packages/mosaic/index.html
- Project mosaic : less volume, more creativity

Interactive Visualizations
- http://www.statmethods.net/advgraphs/interactive.html
- Review : http://ouzor.github.io/blog/2014/11/21/interactive-visualizations.html
- in Python : http://jakevdp.github.io/blog/2014/01/10/d3-plugins-truly-interactive/
- html widgets for R
- rCharts pacakge
- RGraph : Interactive JavaScript charts for your website
- iPlot package
- igraph: network analysis package
- animation : A gallery of animations in statistics and utilities to create animations
- GoogleVis motion chart
- Interactive graphs and charts in R
dygraph
Plotly
- Plotly https://plot.ly/
- https://plot.ly/~r_user_guide/1167/africa-americas-asia-europe-oceania/
- http://www.inside-r.org/blogs/2015/03/03/plotly-graphs-dominos-new-r-notebook
- http://moderndata.plot.ly/dashboards-in-r-with-shiny-plotly/
- http://moderndata.plot.ly/r-python-matlab-dashboards-graphs-with-d3-js-webgl/
- http://blog.revolutionanalytics.com/2014/05/ropensci-and-plotly-make-ggplots-shareable-interactive-and-with-d3.html