R Graphics Lori Shepherd-Kirchgraber May 22, 2012.
Transcript of R Graphics Lori Shepherd-Kirchgraber May 22, 2012.
R Graphics
Lori Shepherd-Kirchgraber
May 22, 2012
demo(“graphics”)
Navigating Devices
• windows( ) Opens a new device [X11() on linux]
• dev.cur( ) Returns current/active device• dev.set( ) Sets a device to current/active
device• dev.off( ) Closes a device• graphics.off( ) Closes all open devices
Some plot calls will open a new device if one is not already open: Plot Hist Boxplot Pie Layout Par change default plot settings
par( )
Argument
• bg• fg
• new• mfrow, mfcol• mai
Controls
• Background Color of plot • Foreground Color of plot
• Add plot to existing, overlay plots • Define multiple plots layout • Adjust plot margins
plot(1:10,1:10) # default white, black
par(bg="pink") # bg changes background color, but only for active deviceplot(1:10,1:10)
windows() # opens new window in windows/mac, X11() for linux plot(1:10,1:10)
windows()par(bg="gray88", fg="red") # fg changes foreground color plot(1:10,1:10)
dev.cur() # give current device
dev.set(2) # set current device plot(10:1, 1:10) # NOTE: this overwrites original
dev.off() # default closes active, can give device number to close inactive
graphics.off() # closes all devices
plot(1:10,1:10) par(bg="pink")
par(bg="gray88", fg="red")
Device Number 3 Is Active
Device Number 2 Is Inactive
What would we want to change?
Title and Axes Labels
Argument• main• sub• xlab • ylab
controls• overall title for the plot• sub title for the plot• title for x axis• title for y axis
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x values“, ylab=“y values”)
For now we will use default setting and discuss options (colors, fonts, etc.) throughout the presentation
Changing Colors
Argument
• col • col.main• col.sub• col.lab• col.axis
Controls
• Plotting color• Color for main title• Color for sub title • Color for x and y labels • Color for axis annotation
• par(bg= , fg= )
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x values", ylab="y values", col="blue", col.main="Purple", col.sub="red", col.lab="orange", col.axis="green")
Colors Choices
• colors( )
Generators: [colors given are in rgb format #RRGGBB]• rainbow( )• heat.colors( )• terrain.colors( )• topo.colors( )• cm.colors( )• gray( ), grey( )• hsv
col argument
• Single Value all points the same
• Length of x/y each point unique color
• Shorter length vector recycled, repeat colors
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x values“, ylab=“y values”, col=“blue”)
col=rainbow(10) col=c(rep(“blue”,5), rep(“red”, 5))
col=c(“blue”, “red”, “green”)
Changing Size
Argument• cex • cex.main• cex.sub• cex.lab• cex.axis
Controls• Plotting size• Size for main title• Size for sub title • Size for x and y labels • Size for axis annotation
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x values", ylab="y values", col="blue", cex=3, cex.main=5, col.sub=0.5, col.lab=1.5, col.axis=2)
Note: If you make your size too big, points will overlap or titles and labels will get cut off
cex argument
• Single Value all points the same
• Length of x/y each point unique size
• Shorter length vector recycled, repeat size
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x value", ylab="y value", cex=1:3)
lwd argument• Controls the width of the lines drawn
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x value", ylab="y value", col=“blue”)
plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x value", ylab="y value", col=“blue”, lwd=5)
Changing Plotting Symbolspch argument
pch controls the plotting symbol used
we have been using pch=1 for open circles
Options• pch=NA, pch=“ “ # no symbol
• 1:18 # S compatible vectors
• 19:25 # R vector symbols, color filled symbols,
includes symbol borders
• 26:31 # unused, ignored
• 32:127 # ASCII
• 128:255 # native characters
plot(1:18, rep(1,18), pch=1:18, cex=2, ylab="")
plot(x=19:25, y=rep(1,7), pch=19:25, cex=2, ylab=“”, col=“black”)
plot(x=19:25, y=rep(1,7), pch=19:25, cex=2, ylab=“”, bg=“black”, col=“red”, lwd=2)
ASCII Symbols
plot(32:127, rep(1,96), pch=32:127, ylab="")
plot(128:255, 128:255, pch=128:255, ylab="")
pch argument
• Single Value all points the same
• Length of x/y each point unique symbol
• Shorter length vector recycled, repeat symbol
plot(1:10, 1:10, cex=1:3, pch=1:3)
Changing Plotting Type type argument
Argument Value• “p” (default)• “l”• “b”• “c”• “o”• “h”• “s”• “S”• “n”
Plotting Type• Points• Lines• Both points and lines• Lines parted at point location• Both “overplotted”• Histogram like – vertical lines• Steps – horizontal then vertical• Steps – vertical then horizontal• No plotting
plot(1:10, 1:10, type=“p”) plot(1:10, 1:10, type=“l”) plot(1:10, 1:10, type=“b”)plot(1:10, 1:10, type=“c”) plot(1:10, 1:10, type=“o”) plot(1:10, 1:10, type=“h”)plot(1:10, 1:10, type=“s”) plot(1:10, 1:10, type=“S”) plot(1:10, 1:10, type=“n”)
Changing Line Type and Width
• lwd # controls width of line
• lty # controls type of line drawn 0 blank 1 solid (default) 2 dashed 3 dotted 4 dotdash 5 longdash 6 twodash
plot(1:10, 1:10, type=“l”, plot(1:10, 1:10, type=“l”, plot(1:10, 1:10, type=“l”, lty=1) lty=2) lty=3)
plot(1:10, 1:10, type=“l”, plot(1:10, 1:10, type=“l”, plot(1:10, 1:10, type=“l”, lty=4) lty=5) lty=6)
Adding to Existing Plot
• points• lines• abline• legend• text• shapes/symbols
• par(new=T)
Watch your plot range
• Xlim• Ylim • Zlim - if applicable
These help set the limit or range of axis values# or specify the x range and y range with xlim and ylim
# xlim=c(xlowerlimit, xupperlimit)# ylim=c(ylowerlimit, yupperlimit)
plot(1:10,1:10, xlim=c(0,13), ylim=c(-2,10))
Orange
# plot everything so that the range is covered plot(circumference~age, data=Orange, type="n")
# plot points for tree 1points(circumference~age, data=Orange, subset=which(Tree==1), pch=21, bg="blue")
# plot line for tree 1lines(stats::lowess(Orange[which(Orange$Tree==1),c(2,3)]), col="blue")
# plot points for tree 4points(circumference~age, data=Orange, subset=which(Tree==4), pch=8,col="hotpink")
# plot line for tree 4 lines(stats::lowess(Orange[which(Orange$Tree==4),c(2,3)]), col="hotpink", lty=2)
Adding Straight Lineabline
abline is a function to plot straight lines• V plot a vertical line at x value
• H plot a horizontal line at y value
• A, B plot a line with slope of a and intercept of b
abline(h=100, lwd=2, col="lightgray")
Adding A Legend
Location of legend specified with• x, y coordinate • "bottomright", "bottom", "bottomleft", "left", "topleft", "top",
"topright", "right" and "center" • locator(n=1)
Legend Arguments
Argument
• legend• fill• lty,lwd• pch• bty
• Bg, box.lty, box.lwd, box.col
• text.col, text.font, text.width• horiz
controls
• Text/Labels • Symbol box fill color• Line type and width• Symbol• If box around legend should be
drawn, either ‘o’ or ‘n’• Background color of legend box,
Border of box line type, width, and color
• Text color, font, and width• T or F, T sets legend horizontal
rather than vertical
legend("topleft", legend=c("Tree1", "Tree4"), fill=c("blue", "hotpink"))
legend(0,150, legend=c("Tree1", "Tree4"), fill=c("blue", "hotpink"), lty=c(1,2), box.col="gray92",col=c("blue", "hotpink"))
legend(locator(1), legend=c("Tree1", "Tree4"), pch=c(21,8), col=c("blue", "hotpink"),bty='n', text.col=c("blue", "hotpink"), horiz=T)
Adding Text
Location of legend specified with• x, y coordinate • locator( )
pos argument controls where text is placed
1=below given location
2=left of given location
3=above given location
4=right of given location
Other arguments to customize: cex, col, font
text(locator(2), labels=c("3rd","6th"), pos=c(3,4))
Adding Shapes and Symbols
• rect( )• polygon( )• symbols( )
Reminder: You can get help on any R function by using ?
?rect
Adding Plots
• sometimes you want to combine plots that by default open a new device or overwrite existing
An Example: a histogram and a density plot
x=rnorm(1000)
hist(x, freq=F)
plot(density(x))
In this case, the density plot will overwrite the histogram
par( )
Argument
• bg• fg
• new
• mfrow, mfcol• mai
Controls
• Background Color of plot • Foreground Color of plot
• Add plot to existing, overlay plots
• Define multiple plots layout • Adjust plot margins
Note: Each plot will by default still plot its own axes and labels
x=rnorm(1000)
hist(x, freq=F, axes=F, main=“”, xlab=“”, ylab=“”)
par(new=T)
plot(density(x) , axes=F, main=“”, xlab=“”, ylab=“”, col=“red”, lwd=2)
Adding Axes axis( )
(used axes=F in plotting call or to add more)
• side # 1 = bottom, 2=left, 3=top, 4=right
• at # where the ticks are drawn
• labels # text for ticks
• tick # T or F, if tic and axes should be drawn
• line # number of lines into the margin to draw, pushes outward
• lwd, col, lty # width, color and line type of axis line
• lwd.ticks, col.ticks # width and color of tick marks
• las # position of labels 1=always horizontal,
2=perpendicular to axis, 3=always vertical
plot(1:10,1:10, axes=F, xlab="", ylab="")box(col="red", lty=3)axis(1)axis(2, at=seq(2,10,by=2), labels=c("a","b","c","d","e"), col.axis="blue", col.ticks="green", col="orange")axis(2, line=2)axis(3, las=2, lwd=2, lwd.ticks=4, col.ticks="blue", lty=2)axis(4, las=1, tick=F)
Adding Title and Labelstitle( )
(used main=“ “, xlab=“ “, ylab=“ “ in plot call)
argument
• main• sub• xlab• ylab
adds
• Overall title for plot• Sub title for plot• X label for plot • Y label for plot
Other arguments for customization: col, col.main, cex, cex.lab, line, family, font.main, font, etc.
Fonts
• Family– Name of font family. Currently supported families:
Sans, serif, mono,
Hershey families (HersheySerif, HersheyGothicEnglish, etc.)
• font, font.axis, font.lab, font.main, font.sub– Numeric
1 = plain text, 2=bold, 3=italic, 4=bold italic
[some families may not support all of these]
plot(1:10,1:10, axes=F, xlab="", ylab="")
box()
title(main="my title", family="mono",font.main=4, col.main="gray50", cex=4)title(xlab="My X value", family="HersheyGothicGerman")title(ylab="My Y value", font.lab=3, line=.5, col.lab="green")
Other Plots
Histogram
argument
• x• Breaks
• Freq• density• angle• labels• col, border• main, xlab, ylab
controls
• Values• How to determine breaks – a vector of break points, a
single value for number of cells (plus tails), or an algorithm for breaks (Sturges, Scott, Freedman-Diaconis)
• T or F, if False it plots density • Density of shading lines, if NA or not specified: none• Slope of shading lines given in degrees• Labels to be placed above each bar • Color to fill bars, border color around bars • Main title of plot, x and y labels
hist(x) hist(x, breaks=4)
X=LakeHuron
hist(x, border="red“, col=c("purple", "violetred1", "green3", "cornsilk", "cyan", "black“,”red”))
hist(x, density=20, angle=c(60,120,180,240,300,0), border="red", col=c("purple", "violetred1", "green3","cornsilk", "cyan", "black“, ”red”), labels=paste("vec ",rep(1:7),sep=""))
legend("topright", density=30, angle=c(60,120,180,240,300,0), border="red", fill=c("purple", "violetred1", "green3","cornsilk", "cyan", "black“,”red”), legend=paste("vec ",rep(1:7),sep=""))
Barplot
argument
• height• besides• horiz• density• angle• col, border• space
controls
• Either vector or matrix • T or F, if F stacked bars, T juxtaposed bars• T or F, if False bars are drawn vertically• Density of shading lines, if NA or not specified: none• Slope of shading lines given in degrees• Color to fill bars, border color around bars • The amount of space between groups/bars
VADeaths
barplot(VADeaths) barplot(VADeaths, beside=T)
barplot(VADeaths, beside=T, col=c(“lightblue”,"mistyrose","lightcyan","lavender", "cornsilk"), legend = rownames(VADeaths), ylim = c(0, 100), cex.names=.5)
For confidence intervalsCheck out the plotrix package’s
plotCI function
library(plotrix)?plotCI
Pie Chart
argument
• x• labels• radius• density• angle• col, border
controls
• Numeric vector for slices• Vector names for slices• Numeric: radius of plot • Density of shading lines, if NA or not specified: none• Slope of shading lines given in degrees• Color to fill bars, border color around bars
pie.sales <- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12)names(pie.sales) <- c("Blueberry","Cherry","Apple","Boston Cream",
"Other", "Vanilla Cream")clr=c(“red”,”purple”,”blue”,”cyan”,”green”,”yellow”)
pie(pie.sales) pie(pie.sales, col = clr, radius=0.5)
pie(pie.sales, col=clr, border=NA, labels="")
pie(pie.sales, col=clr, density=10, angle= 15 + 10 * 1:6, lty=2, lwd=2, border="gray69", main="Pie Sales")
Image
Image
Argument
• Z• X, Y
• xlim,ylim,zlim• col
Control
• Matrix of values to plot• Location of grid lines, if omitted created
based on Z• Set range of axes values• Color scale to use for plot
– Default is heat.colors(12)
Mat = matrix(1:12,ncol=3)
1 5 92 6 103 7 114 8 12
image(Mat)
image(Mat, col=terrain.colors(12))
Volcano
x <- 10*(1:nrow(volcano))y <- 10*(1:ncol(volcano))image(x, y, volcano, col = terrain.colors(100), axes = FALSE)contour(x, y, volcano, levels = seq(90, 200, by = 5), add = TRUE, col = "peru")
Another way to define colorhsv
• Hue, saturation and value• Creates a vector of colors
– Transitions for color of hue to black
image(x, y, volcano, col=hsv(0.5,v=seq(1,0,length=10)), axes=FALSE)
image(x, y, volcano, col=hsv(0.5,v=seq(0,1,length=10)), axes=FALSE)
image(x, y, volcano, col=c(hsv(0.5,v=seq(1,0,length=10)), hsv(h=0,v=seq(0,1,length=10))) axes=FALSE)
Color gradient in hsv
• Numeric value for h (hue)
Uploading A Picture
• Utilizes the R packages– plotrix– png
• Upload a .png file using readPNG• Use the rasterImage to convert into bitmap
formatting and place onto plot
library(plotrix)library(png)
# load image readPNGimg <- readPNG("worldMapWikipedia.png")
# create blank plot plot(1:10,1:10, type="n", axes=F, xlab="", ylab="")
# add image to given location xleft, ybottom, xright, ytop rasterImage(img, 1,1,10,10)
text(locator(2), pos=4, col="black", font=2, lwd=3, cex=0.5, labels=c("USA“,”China”))
Multiple Plots
par( )
Argument
• bg• fg• new• mfrow, mfcol• mai
Controls
• Background Color of plot • Foreground Color of plot• Add plot to existing, overlay plots • Define multiple plots layout • Adjust plot margins
mfrow, mfcol
• c(Number of rows, Number of Columns)• mfrow fills by row• mfcol fills by col
par(mfrow=c(2,2)) par(mfcol=c(2,2))
plot(0,0, main="plot1")plot(1:10,1:10, col="blue", main="plot2")plot(1:10,10:1, col="red", main="plot3")plot(1:3,1:3, main="plot4")
par(mfrow=c(2,3))plot(1:10, 1:10, type=“l”, lty=1)plot(1:10, 1:10, type=“l”, lty=2)plot(1:10, 1:10, type=“l”, lty=3)plot(1:10, 1:10, type=“l”, lty=4)plot(1:10, 1:10, type=“l”, lty=5)plot(1:10, 1:10, type=“l”, lty=6)
Layoutmat is a numeric matrix with numbers 1:number of desired plots.0 indicates area with no plot
4 4 4 4 4 4 4 4 0 0 0 0 04 4 4 4 4 4 4 4 0 0 0 0 01 1 1 1 1 1 1 1 3 3 3 3 31 1 1 1 1 1 1 1 3 3 3 3 31 1 1 1 1 1 1 1 3 3 3 3 31 1 1 1 1 1 1 1 3 3 3 3 31 1 1 1 1 1 1 1 3 3 3 3 31 1 1 1 1 1 1 1 3 3 3 3 32 2 2 2 2 2 2 2 3 3 3 3 32 2 2 2 2 2 2 2 3 3 3 3 32 2 2 2 2 2 2 2 3 3 3 3 32 2 2 2 2 2 2 2 3 3 3 3 3
mat = matrix(c(rep(c(rep(4,8),rep(0,5)),2), rep(c(rep(1,8),rep(3,5)),6), rep(c(rep(2,8),rep(3,5)),4)),byrow=T, ncol=13)
Layout: common error
Error in plot.new() : figure margins too large
par( )
Argument
• bg• fg• new• mfrow, mfcol• mai
Controls
• Background Color of plot • Foreground Color of plot• Add plot to existing, overlay plots • Define multiple plots layout • Adjust plot margins
par(mai=c(bottom, left, top, right))Bottom, left, top, and right are numeric values corresponding to margins around the plot
mat = matrix(c(rep(c(rep(4,8),rep(0,5)),2), rep(c(rep(1,8),rep(3,5)),6), rep(c(rep(2,8),rep(3,5)),4)), byrow=T, ncol=13)
layout(mat)
par(mai=c(.5,.5,.5,.5))boxplot(count ~ spray, data = InsectSprays, col = 'lightgray')
par(mai=c(.5,.5,.5,.5))plot(1:3,1:3, col='blue', xlab='', ylab=''); points(1:2, 2:3, col='red')
par(mai=c(.5,.5,0,.1))image(1:2,1:3, z=matrix(c(-1,-10,1,10,-5,0),ncol=3,nrow=2), xlab='', ylab='')
par(mai=c(.1,.3,.1,.1))plot(cos, xlim = c(-pi,3*pi), n = 1001, col = 'blue', xlab='', ylab='')
Saving
• savehistory• > File > save as• savePlot• png, jpeg, bmp, tiff, postscript, pdf
savehistory
savehistory(“myRcode”)
savehistory(nameOfFile)
This saves a text file with all the code from that R session. This code can be loaded into a new R session or you can use the text file to copy and paste needed code.
loadhistory(“myRcode”)
Code will not appear in R console but code is in session memory. You are able to access the code by scrolling.
> File > Save as This will save whatever plot window was last clicked on NOT active device
savePlot
argument• filename• type
• device
controls
• Name of file• File type for saving. Currently supported types:
"wmf", "emf", "png", "jpg", "jpeg", "bmp", "tif", "tiff", "ps", "eps", "pdf“
• Number indicating which device should be saved. If unspecified the default saves the current device (Active device)
savePlot(“saveThisPlot”, type=“jpeg”)
plot(1:10,1:10)windows()par(bg="pink")plot(1:10,1:10)
# this saves plot with pink backgroundsavePlot(“saveThisPlot”, type=“jpeg”)
# this saves plot with white backgroundsavePlot(“saveOrigPlot”, type=“pdf”, device=2)
Saving using R functions
• png• jpeg• bmp• tiff• postscript• pdf
These need to be called BEFORE making the plot
png(“myPNGfile.png”)
< code to generate plot >
dev.off()
png("test.png") par(bg=“pink”) plot(1:10,1:10) lines(1:10,1:10)dev.off()
png, bmp, jpeg, tiff
• Will only save one plot per file
• To save multiple plots, %d in the filename – This will generate plots with the same base
filename but add a numeric indicator
jpeg("test%d.jpeg") plot(1:10,1:10) par(bg="pink") plot(1:10,1:10)dev.off()
postscript and pdf
• Can have multiple plots in one file
• Each plot will have a new page
3D plots
See R packages: • rgl • scatterplot3d
rgl
library(“rgl”)demo(“rgl”)
plot3d(rnorm(20), rnorm(20), rnorm(20), xlab=“x”, ylab=“y”, zlab=“z”)points3d(rnorm(10), rnorm(10), rnorm(10), col=“Red”) lines3d(rnorm(5), rnorm(5), rnorm(5), col=“blue”)
Exporting Interactive Plots
Sendplot
What is sendplot?
sendplot generates an interactive layout of plots.
each plot may be interactive or static
What is meant by interactivity is that information specific to a point or image region is displayed when the mouse scrolls over the area
A png file and an html file are sent to end user; it can be sent to and run on any machine with a web browser that has javascript capabilities
End ResultResult is two files:
1. png file2. html file
The researcher/collaborator need only to openthe html file in order to have an interactive graphto view data.
It can be customized on the programmers end to show any data the researcher requests or would find useful
library("sendplot")Mtcars
y.pos=mtcars$mpgx.pos=mtcars$hpplot(x.pos,y.pos,xlab='gross horsepower', ylab='miles per gallon', axes=F, pch=mtcars$cyl,col=mtcars$am+1,cex=0.875,main='Motor Trend Car Road Tests')axis(1)axis(2)legend(200,30,pch=rep(c(4,6,8),2), col=c(rep(1,3),rep(2,3)), legend=paste(rep(c(4,6,8),2),'cylinders,', c('automatic','manual')[c(rep(1,3), rep(2,3))]), cex=0.875)
plot.call=c(“plot(x.pos,y.pos,xlab='gross horsepower', ylab='miles per gallon', axes=F,pch=mtcars$cyl, col=mtcars$am+1,cex=0.875, main='Motor Trend Car Road Tests'); axis(1); axis(2); legend(200,30,pch=rep(c(4,6,8),2), col=c(rep(1,3),rep(2,3)), legend=paste(rep(c(4,6,8),2),'cylinders,', c('automatic','manual')[c(rep(1,3),rep(2,3))]), cex=0.875)")
xy.labels = data.frame(name=rownames(mtcars),mtcars=mtcars)
xy.send(plot.call=plot.call, y.pos=y.pos, x.pos=x.pos, xy.labels = xy.labels, image.size="800x600", fname.root="exPlotXY", font.size=18)
Code to Make Plot
Sendplot Code