R Graphics Lori Shepherd-Kirchgraber May 22, 2012.

Slides:



Advertisements
Similar presentations
Introduction to R Graphics
Advertisements

Graphics in R data analysis and visualization Katia Oleinik Scientific Computing and Visualization Boston University
1 Cascading Style Sheets Continued Different kinds of selectors in a style sheet –Simple- Pseudo-Class –Contextual- Pseudo-Element –Class Image Styles.
Cascading Style Sheets. CSS stands for Cascading Style Sheets and is a simple styling language which allows attaching style to HTML elements. CSS is a.
CREATING A MULTIPLE PAGE REPORT Presented by: Dr. Ennis-Cole.
Microsoft Word Review.
FIRST COURSE Excel Tutorial 4 Working with Charts and Graphics.
© by Pearson Education, Inc. All Rights Reserved. continued …
Customizing Graphs Base graphics options. plot() The workhorse plotting function plot(x) plots values of x in sequence or a barplot plot(x, y) produces.
Evan Girvetz Winkenwerder Introduction to Graphics in R © R Foundation, from
Creating a Web Page with Tables. Objectives Create a text table with preformatted text Create the basic structure of a graphical table Organize table.
COMPREHENSIVE Excel Tutorial 4 Working with Charts and Graphics.
COMPREHENSIVE Excel Tutorial 2 Formatting a Workbook.
XP New Perspectives on Microsoft Office Excel 2003 Tutorial 4 1 Microsoft Office Excel 2003 Tutorial 4 – Working With Charts and Graphics.
Baburao Kamble (Ph.D) University of Nebraska-Lincoln Data Analysis Using R Week5: Charts/Plots in R.
Instructor: Professor Cora Martinez, PhD Department of Civil and Environmental Engineering Florida International University.
Adobe Illustrator CS2 — Revealed GRADIENTS CREATING TEXT AND.
Chapter 5 Review: Plotting Introduction to MATLAB 7 Engineering 161.
Excel Part 2 Formatting a Workbook. XP Objectives Format text, numbers, and dates Change font colors and fill colors Merge a range into a single cell.
An Introduction to R graphics Elizabeth Garrett-Mayer Slides borrowed from Cody Chiuzan & Delia Voronca March 24, 2014.
AN INTRODUCTION TO GRAPHICS IN R. Today Overview Overview –Gallery of R Graph examples High-Level Plotting Functions High-Level Plotting Functions Low-Level.
Graphics in R. X
R-Graphics Day 2 Stephen Opiyo. Basic Graphs One of the main reasons data analysts turn to R is for its strong graphic capabilities. R generates publication-ready.
Sendplot Lori Shepherd April 06, sendplot The Problem: The Approach: How can we quickly generate useful data and get it back to scientists/collaborators.
Microsoft Excel Spreadsheet Review. Templates  Templates can be produced for the following elements:  Text and Graphics  Formatting Information – Layouts,
Chapter 9 Creating and Designing Graphs. Creating a Graph A graph is a diagram of data that shows relationship among a set of numbers. Data can be represented.
Creating Charts for the Agency Budget Creating Budget Charts, Slide 1Copyright © 2004, Jim Schwab, University of Texas at Austin.
An Introduction to R graphics Cody Chiuzan Division of Biostatistics and Epidemiology Computing for Research I, 2012.
Microsoft ® Office Excel 2007 Working with Charts.
T U T O R I A L  2009 Pearson Education, Inc. All rights reserved. 1 3 Welcome Application Introduction to Visual Programming.
Copyright 2006 South-Western/Thomson Learning Chapter 12 Tables.
Copyright (c) 2004 Prentice-Hall. All rights reserved. 1 Committed to Shaping the Next Generation of IT Experts. Adding Graphical Elements Essentials for.
CTS130 Spreadsheet Lesson 9 - Building Charts. What is a Chart? A chart is a visual display of information in a worksheet. Charts can help you make comparisons,
Learn R Toolkit D Kelly O'DayBox, Dot, Histogram, Strip Charts Mod 5 –Box Charts: 1 Module 5 Box, Dot, Histogram, Strip Charts Do See & HearRead Learn.
R-Graphics Stephen Opiyo. Basic Graphs One of the main reasons data analysts turn to R is for its strong graphic capabilities. R generates publication-ready.
© 2004 by the McGraw-Hill Companies, Inc. All rights reserved. Lecture 29 Enhancing Presentations with Graphics (2)
CRSD Technology Training Tony Judice. Quick Access Toolbar – can be modifiedSave as… allows you to save the file to a different location and also as an.
Recap Chapter 5 “Plotting” Two Dimensional Plots Simple x-y Plots Titles, Labels and Grids Multiple Plots.
EGR 106 Lecture 6 2-D Plotting Graphical presentation has become the standard method to show technical information. Engineers use plots to analyze, visualize,
R (3) Introduction to Graphics. The main guide R in Action Data Analysis and Graphics with R Robert I. Kabacoff
Scientific Computing (w1) R Computing Workshops An Introduction to Scientific Computing workshop 1.
By: Ms. Abeer Helwa 1. WORD WEB APP 2 Word Web App is a limited version of Word, enabling you to edit, format, and share documents online. Word Web App.
Plotting Complex Figures Using R
Lesson 6 Formatting Cells and Ranges. Objectives:  Insert and delete cells  Manually format cell contents  Copy cell formatting with the Format Painter.
Mapping local community assets online Read this if you want to learn how to: 1)Create online maps of local community assets using Google Maps 2)Allow other.
Cumulative Review of Microsoft Word Mrs. Masishin.
Introduction to Technology. Parts of MSWord Screen Title Bar Quick Access Toolbar Button Ribbon Status Bar (views and zoom)
Tutorial 4 Creating Page Layouts with CSS
Excel Part 4 Working with Charts and Graphics. XP Objectives Create an embedded chart Work with chart titles and legends Create and format a pie chart.
Excel Part 4 Working with Charts and Graphics. XP Objectives Create an embedded chart Work with chart titles and legends Create and format a pie chart.
Web111a_chapt04.ppt HTM: Section 4 Tables Table Types Text table elements Easy to use Use fixed-font text (font family monospace) Andale Mono Courier Monaco.
Introduction to plotting data Fish 552: Lecture 4.
EGR 106 – Week 5 – 2-D Plots Question : Why do engineers use plots? Answer : To analyze, visualize, and present data. Matlab has many useful plotting options.
Review > mean(humidity, na.rm=T) > humidity[!is.na(humidity)] > X x Y Y[[1]][2,3] > zone.fac
 You won’t write a single line of program code.  Instead, you’ll use visual programming techniques.  Visual Studio processes your actions (such as mouse.
Permeability (% of Control)
Permeability (% of Control)
Using R Graphs in R.
Inserting and Working with Images
Lecture 25: Exploring data
Chapter Lessons Create and format text Flow text into an object
Trevor A. Branch FISH 552 Introduction to R
Introduction to R plot Instructor: Li, Han
Welcome To Microsoft Word 2016
Use a Large Bold Type for the Main Title (80 pt):
Permeability (% of Control)
Use a Large Bold Type for the Main Title (80 pt):
Use a Large Bold Type for the Main Title (70 pt):
Permeability (% of Control)
Use a Large Bold Type for the Main Title (70 pt):
Presentation transcript:

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  Parchange 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 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

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 Valueall 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 Valueall 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 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

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

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

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

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 intervals Check 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= * 1:6, lty=2, lwd=2, border="gray69", main="Pie Sales")

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

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

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)

Layout mat is a numeric matrix with numbers 1:number of desired plots. 0 indicates area with no 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: 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 background savePlot(“saveThisPlot”, type=“jpeg”) # this saves plot with white background savePlot(“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”)  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 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

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

Questions? Lori Shepherd-Kirchgraber