880 likes | 1.03k Views
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 d ev.off ( ) Closes a device
E N D
R Graphics Lori Shepherd-Kirchgraber May 22, 2012
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 Controls Background Color of plot Foreground Color of plot Add plot to existing, overlay plots Define multiple plots layout Adjust plot margins • bg • fg • new • mfrow, mfcol • mai
plot(1:10,1:10) # default white, black par(bg="pink") # bg changes background color, but only for active device plot(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
Title and Axes Labels Argument controls overall title for the plot sub title for the plot title for x axis title for y axis • main • sub • xlab • ylab • For now we will use default setting and discuss options (colors, fonts, etc.) throughout the presentation plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x values“, ylab=“y values”)
Changing Colors • par(bg= , fg= ) Argument Controls Plotting color Color for main title Color for sub title Color for x and y labels Color for axis annotation • col • col.main • col.sub • col.lab • col.axis 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=c(“blue”, “red”, “green”) col=rainbow(10) col=c(rep(“blue”,5), rep(“red”, 5))
Changing Size Argument Controls Plotting size Size for main title Size for sub title Size for x and y labels Size for axis annotation • cex • cex.main • cex.sub • cex.lab • cex.axis • Note: If you make your size too big, points will overlap or titles and labels will get cut off 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)
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”, lwd=5) plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x value", ylab="y value", col=“blue”)
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(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="")
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 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 • “p” (default) • “l” • “b” • “c” • “o” • “h” • “s” • “S” • “n”
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 1 points(circumference~age, data=Orange, subset=which(Tree==1), pch=21, bg="blue") # plot line for tree 1 lines(stats::lowess(Orange[which(Orange$Tree==1),c(2,3)]), col="blue") # plot points for tree 4 points(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 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 • fill • lty,lwd • pch • bty • Bg, box.lty, box.lwd, box.col • text.col, text.font, text.width • horiz
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 Controls Background Color of plot Foreground Color of plot Add plot to existing, overlay plots Define multiple plots layout Adjust plot margins • bg • fg • new • mfrow, mfcol • mai 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 Labels title( ) (used main=“ “, xlab=“ “, ylab=“ “ in plot call) argument adds Overall title for plot Sub title for plot X label for plot Y label for plot • main • sub • xlab • ylab 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")
Histogram argument 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 • x • Breaks • Freq • density • angle • labels • col, border • main, xlab, ylab
X=LakeHuron hist(x) hist(x, breaks=4)
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 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 • height • besides • horiz • density • angle • col, border • space VADeaths