Presentation is loading. Please wait.

Presentation is loading. Please wait.

R Graphics Lori Shepherd-Kirchgraber May 22, 2012.

Similar presentations


Presentation on theme: "R Graphics Lori Shepherd-Kirchgraber May 22, 2012."— Presentation transcript:

1 R Graphics Lori Shepherd-Kirchgraber May 22, 2012

2 demo(“graphics”)

3 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  Parchange default plot settings

4 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

5 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

6 plot(1:10,1:10)par(bg="pink") par(bg="gray88", fg="red")

7 Device Number 3 Is Active Device Number 2 Is Inactive

8 What would we want to change?

9 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

10 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")

11 Colors Choices colors( ) Generators: [ colors given are in rgb format #RRGGBB ] rainbow( ) heat.colors( ) terrain.colors( ) topo.colors( ) cm.colors( ) gray( ), grey( ) hsv

12 col argument Single Valueall points the same Length of x/y each point unique color Shorter length vector recycled, repeat colors

13 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”)

14 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

15 cex argument Single Valueall points the same Length of x/y each point unique size Shorter length vector recycled, repeat size

16 plot(x=1:10, y=1:10, main="My Title", sub="and sub title", xlab="x value", ylab="y value", cex=1:3)

17 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)

18 Changing Plotting Symbols pch 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

19 plot(1:18, rep(1,18), pch=1:18, cex=2, ylab="")

20 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)

21 ASCII Symbols plot(32:127, rep(1,96), pch=32:127, ylab="")

22 plot(128:255, 128:255, pch=128:255, ylab="")

23 pch argument Single Valueall 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)

24 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

25 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”)

26 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

27 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)

28 Adding to Existing Plot points lines abline legend text shapes/symbols par(new=T)

29 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))

30 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)

31 Adding Straight Line abline abline is a function to plot straight lines Vplot a vertical line at x value Hplot 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")

32 Adding A Legend Location of legend specified with x, y coordinate "bottomright", "bottom", "bottomleft", "left", "topleft", "top", "topright", "right" and "center" locator(n=1)

33 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

34 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)

35 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))

36 Adding Shapes and Symbols rect( ) polygon( ) symbols( ) Reminder: You can get help on any R function by using ? ?rect

37 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

38 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

39 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)

40 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

41 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)

42 Adding Title and Labels title( ) (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.

43 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]

44 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")

45 Other Plots

46 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

47 hist(x)hist(x, breaks=4) X=LakeHuron

48 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=""))

49 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

50 barplot(VADeaths) barplot(VADeaths, beside=T)

51 barplot(VADeaths, beside=T, col=c(“lightblue”,"mistyrose","lightcyan","lavender", "cornsilk"), legend = rownames(VADeaths), ylim = c(0, 100), cex.names=.5)

52 For confidence intervals Check out the plotrix package’s plotCI function library(plotrix) ?plotCI

53 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

54 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")

55 Image

56 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)

57 Mat = matrix(1:12,ncol=3) 1 5 9 2 6 10 3 7 11 4 8 12 image(Mat) image(Mat, col=terrain.colors(12))

58 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")

59 Another way to define color hsv 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)

60 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)

61 Color gradient in hsv Numeric value for h (hue)

62 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

63 library(plotrix) library(png) # load image readPNG img <- 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”))

64 Multiple Plots

65 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

66 mfrow, mfcol c(Number of rows, Number of Columns) mfrow fills by row mfcol fills by col

67 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")

68 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)

69 Layout mat 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 0 1 1 1 1 1 1 1 1 3 3 3 3 3 2 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)

70 Layout: common error Error in plot.new() : figure margins too large

71 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

72 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='')

73 Saving savehistory > File > save as savePlot png, jpeg, bmp, tiff, postscript, pdf

74 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.

75 > File > Save as This will save whatever plot window was last clicked on NOT active device

76 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”)

77 plot(1:10,1:10) windows() par(bg="pink") plot(1:10,1:10) # this saves plot with pink background savePlot(“saveThisPlot”, type=“jpeg”) # this saves plot with white background savePlot(“saveOrigPlot”, type=“pdf”, device=2)

78 Saving using R functions png jpeg bmp tiff postscript pdf These need to be called BEFORE making the plot

79  png(“myPNGfile.png”)  dev.off() png("test.png") par(bg=“pink”) plot(1:10,1:10) lines(1:10,1:10) dev.off()

80 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()

81 postscript and pdf Can have multiple plots in one file Each plot will have a new page

82 3D plots See R packages: rgl scatterplot3d

83 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”)

84 Exporting Interactive Plots Sendplot

85 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

86 End Result Result is two files: 1. png file 2. html file The researcher/collaborator need only to open the html file in order to have an interactive graph to view data. It can be customized on the programmers end to show any data the researcher requests or would find useful

87 library("sendplot") Mtcars y.pos=mtcars$mpg x.pos=mtcars$hp 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) 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

88 Questions? Lori Shepherd-Kirchgraber las65@buffalo.edu


Download ppt "R Graphics Lori Shepherd-Kirchgraber May 22, 2012."

Similar presentations


Ads by Google