Upload
bona
View
23
Download
0
Embed Size (px)
DESCRIPTION
Module 4 R Charts. Do. Learn. See & Hear. Read. PowerPoint must be in View Show Mode to See videos and hyperlinks. Module 4 R Graphics Menu. Making a Graphic Script Working with plot() Function Adding Text to a Chart Adding Lines to Chart Extra R Scripts. Menu. - PowerPoint PPT Presentation
Citation preview
D Kelly O'Day R Charts Mod 4 - R Charts: 1
Learn R Toolkit
Module 4R Charts
Do
See & Hear Read
Learn
PowerPoint must be in View Show Mode to See videos and hyperlinks
D Kelly O'Day R Charts Mod 4 - R Charts: 2
Learn R Toolkit
Module 4 R Graphics Menu
• Making a Graphic Script
• Working with plot() Function
• Adding Text to a Chart
• Adding Lines to Chart
• Extra R Scripts
D Kelly O'Day R Charts Mod 4 - R Charts: 3
Learn R Toolkit
Making a Graphic ScriptMenu
Click video image to start video
D Kelly O'Day R Charts Mod 4 - R Charts: 4
Learn R Toolkit
Making a Graphic Script
• R’s Graphic Packages
• R’s 3 Distinct Chart Areas
• Script Components
– High level functions
– Graphic parameters
– Low level Functions
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 5
Learn R Toolkit
R’s Graphics Packages
• R has several graphics subsystems:
– Graphics – traditional graphics
– Grid package (low level functions)
– Lattice package
– ggplot2 package
• This module shows the traditional - base graphics system
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 6
Learn R Toolkit
R’s 3 Distinct Chart Areas
• R’s 3 Chart Areas:
1. Plot Area – within axes
2. Figure Margin Area – for axis labels and tick mark labels
3. Outer Margin Area
• R gives User precise control over content, format of all 3 Areas
– High Level Graphic Functions
– Graphic Parameters
– Low Level Graphic Functions
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 7
Learn R Toolkit
Making a Graphic Scriptwith R’s Graphic Package
par(oma=c(2,2,2,2)); par(mar=c(3,3,1,1))plot(x_data, y_data, main = “My Chart Title“, type = "b", xlim = c(0,11), ylim = c(0,11), xlab ="X", ylab = "Y“, pch=16, col = "red", bty = "n", xaxs="i", yaxs = "i", las=1) text(2,7, “my note”, col = “blue” )
# R Script to produce scatter chart
x_data <- ...y_data <-…par( ) # Graphic parameters
plot( ) # High level plot function
text( ) # Low level function
Graphic Parameters 70 GPs defaults set
adjust w/ par()
High Level Graphic Function Call
Use GP defaults or
adj GP w/ argument
Low Level GraphicFunction Call
Use GP defaults or
adj GP w/ argument
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 8
Learn R Toolkit
High Level Graphic Functions Produce complete chart
Menu
Type R function()
Bar Chart barplot()
Box & Whisker Plot boxplot()
Dot Plot dotchartt()
Histogram hist()
Scatter Plot plot()
Strip Chart stripchart()
This module focuses on plot() function low level functions, graphic parameters.
Module 5 covers box, dot, histogram and strip charts
D Kelly O'Day R Charts Mod 4 - R Charts: 9
Learn R Toolkit
Low Level Plot FunctionsAdd graphic content to current plot
Menu
grid(nx, ny) Add grid lines to current plot. NA stop grid in corresponding direction
axis(side n,) Add axis at side n to current plot
box(which=, )Add box around current plot, figure or outer margin area depending on which specified
legend Add legend to current plot
arrows(x,y)
lines(x, y)
points(x,y)
Add arrow line, line or points to current plot. type = can be used to specify style (“p”,”b”, “l”, etc)
abline(a,b)
abline(h or v=)
Add line to current plot. a is intercept, b is slope.
h/v for horizontal/ vertical line
segments(x0,x1, y0,y1) Add line segment(s) between pairs of points
polygon(x,y) Add polygon defined by vectors x and y
text(x,y, “note”) Add text to current plot at x & y
D Kelly O'Day R Charts Mod 4 - R Charts: 10
Learn R Toolkit
Graphic ParametersGP
• R has 70 Graphic Parameters (GP)• Each GP has:
– name: col = – value: “red”
• Default Values Set At start of R session
• To Get par() values– par() lists all 70 with current
value– par(“GP_name”) gives current
value for specific GP• User can change GP value:
– Global: par(“col” = “red”)– Local: plot(x,y, col=“red”)
> par(“col”)[1] “black”
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 11
Learn R Toolkit Essential Graphical Parameters
* These parameters must be set with call to par().
Menu
adj= Text string justification: 0=left, 0.5=centered, 1=right
ann= T or F controls plot annotation
bg= Background color
bty= Type of box around plot: “n”=none, “l” = x & y, “o” = full
cex= Magnification ratio for text relative to default point size
col= Color specification. R accepts “red”, “blue”, “dark grey”, etc names for 657 colors
las= Style of tick mark labels: 0=parallel to axis, 1 =always horizontal, 3=always vertical
lty= Line type: 0=blank, 1=solid, 2=dashed, 3=dotted, 4=dotdash, 5=longdash, 6=twodash
lwd= Line width, default is 1.
* mar=, oma= Vector c(b,l,t,r) that sets number of lines for margin and outer margin areas by axis #
* mfcol=, mfrow= Vector c(nr,nc) to specify multiple plots. mfcol draws by columns, mfrow by row
pch= Integer specifying a symbol to be used in plotting points
* ps= Point size of text, not symbols
* pty= Plot region: s=square, m=maximum
srt= String rotation in degrees
* xaxs=, yaxs= Style of axis: “r” = offset of x & y to prevent points overplotting axis, “i” = no offset
D Kelly O'Day R Charts Mod 4 - R Charts: 12
Learn R Toolkit
pch = Plot Characters Graphic Parameter
• R has 25 plotting characters
• pch = specifies plot character
• Characters 19 – 20 can be filled with selected color
o 19 – Solid circle
o 20 – Bullet circle
• Characters 21: 25 can have selected fill and border colors bg = Controls Border color col= Controls fill
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 13
Learn R Toolkit
lty= Line Type Graphic Parameter Menu
• R has 6 line types
• lty = specifies the line type
• lty= can be specified as integer or character string:
0 – “blank”
1 – “solid”
2 – “dashed”
3 – “dotted”
4 – “dotdash”
5 – “longdash”
6 – “twodash”
•
D Kelly O'Day R Charts Mod 4 - R Charts: 14
Learn R Toolkit
Assignment 4-1Getting Familiar with par()
1. Print out par documentation ?par2. Get Current Values for all par()3. Get current par(“bty”) value
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 15
Learn R Toolkit
Working with plot() Function
Click video image to start video
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 16
Learn R Toolkit
plot() Function ArgumentsMenu
x,y
y~xVectors for x and y values to be plotted
type=
type = “p” – individual points
type = “l” – line
type = “b” – points connected with lines
type = “h” – vertical lines from 0
type = “s” – step chart
main = “ ”
sub = “ ”
Figure title top of plot, large font
Sub title – below X axis, smaller font
xlab = “ ”
ylab = “ ” X and Y axis titles
ann= T or F Should default annotation be included
axes = T or F Set to F when you want custom axis
xlim=c( x1, x2)
ylim=c(y1, y2)Limits of plot for X and Y axes
plot(x,y, type=“?”, main’”??”, sub = “??“, xlab=“??”, ylab =“??”, ann =?, axes = ?, xlim = c(x1,x2), ylim = c(y1,y2))
or
plot(y ~ x, data = “??”, type=“?”, main’”??”, sub = “??“, xlab=“??”, ylab =“??”, ann =?, axes = ?, xlim = c(x1,x2), ylim = c(y1,y2))
D Kelly O'Day R Charts Mod 4 - R Charts: 17
Learn R Toolkit
plot() Function DefaultsMenu
Potential plot() Default Improvements1. Line – symbol style2. X & Y axis do not meet @ 03. Remove box around plot4. Adjust Y axis label orientation5. Improve X & Y axis labels
# R script to demonstrate default plot()
## Ex_Scr_4_1_default_plot.R ################### ##Script to produce default XY plot()## STEP 1: SETUP - Source File rm(list=ls()); par(oma=c(2,1,0,1)) script = "C:/Learn_R/Mod_4_R_Charts/Ex_Scr_4_1_default_plot.R"## STEP 2: READ DATA y_data <- c(0,1,2,3,4,5,6,7,8,9,10,9,8,7,6,5,4,3,2,1,0) x_data <- seq(0:20)## STEP 3: MANIPULATE DATA## STEP 4: PRODUCE CHART - REPORT plot(x_data,y_data, main = "plot() Defaults ") ## Outer Margin annotation my_date <- format(Sys.time(), "%m/%d/%y") mtext(script, side = 1, line = .75, cex=0.7, outer = T, adj = 0) mtext(my_date, side = 1, line =.75, cex = 0.7, outer = T, adj = 1)
D Kelly O'Day R Charts Mod 4 - R Charts: 18
Learn R Toolkit
Improving plot() Function Defaultswith Additional plot() arguments & graphical parameters
Menu
plot(x_data,y_data, main = "plot() Defaults" )plot(x_data,y_data, main = "plot() Default Improvements", type = "b", col = "red", bty = "n", xaxs="i", yaxs = "i", las=1, xlim = c(0,25), ylim = c(0,12), xlab = "X", ylab = "Y" )
D Kelly O'Day R Charts Mod 4 - R Charts: 19
Learn R Toolkit
Working With R Colors
• Users can specify colors by name; R has 657 colors
– “red”
– “blue”
– “darkgreen”
• To get list of R colors:
>colors()
• col = most common way to specify color for lines, points, text
• Alternatives: rgb() and hsv()
• Color Conversions:
– col2rgb()
– convertColor()
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 20
Learn R Toolkit
plot() type argument type=?,
• "p" for points
• "b" for both
• "o" for both ‘overplotted’
• "l" for lines
• "c" for the lines part alone of "b" • "h" for high-density vertical lines
• "s" for h/v stair steps
• "S" for v/h stair steps
• "n" for no plotting
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 21
Learn R Toolkit
Example Scatter plot
## Ex_Scr_4_3_xy_plot.R ################### ##Script to produce scatter plot## STEP 1: SETUP - Source File rm(list=ls()); par(oma=c(2,1,0,1)) script <- "C:/Learn_R/Mod_4_R_Charts/Ex_Scr_4_3_xy_plot.R"## STEP 2: READ DATA x_data <- seq(0,10*pi,0.1*pi) y_data <- sin(x_data)plot(x_data,y_data,type = "l")## Outer margin annotation my_date <- format(Sys.time(), "%m/%d/%y") mtext(script, side = 1, line = .75, cex=0.7, outer = T, adj = 0) mtext(date(), side = 1, line =.75, cex = 0.7, outer = T, adj = 1)
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 22
Learn R Toolkit
Assignment 4-2xy plot ()
• Start R Session
• In R Console, Open Script:“C:/Learn_R/Mod_4_R_Script/Ex_Scr_4_3_xy_plot.R”
• Save as:“C:/Learn_R/Mod_4_R_Script/Practice_4_1_xy_plot.R”
• Make these changes– par() settings:
• par(ps = 10)• par(las = 1)
– plot() formatting:– type = “b”– pch = 16– col = “blue”– xlab = “X”; ylab= “sin(X)”– main = “xy Plot of sin() Formula”– xlim = c(0, 15)– ylim = c(-2, 2)
Menu
Expected Result
D Kelly O'Day R Charts Mod 4 - R Charts: 23
Learn R Toolkit
Assignment 4-2xy plot ()
## Practice_4_1_xy_plot.R ################### ##Script to produce scatter plot## STEP 1: SETUP - Source File rm(list=ls()); par(oma=c(1.75,1,0,1)); par(las=1); par(ps=10) script <- "C:/Learn_R/Mod_4_R_Charts/Practice_4_1_xy_plot.R"## STEP 2: READ DATA x_data <- seq(0,10*pi,0.1*pi) y_data <- sin(x_data)plot(x_data,y_data,type = "b",pch = 16,
col = "blue", xlab ="X", ylab = "sin(X)",main = "xy Plot of sin() Function",xlim = c(0,15), ylim = c(-2,2))
## Outer margin annotation my_date <- format(Sys.time(), "%m/%d/%y") mtext(script, side = 1, line = .5, cex=0.7, outer = T, adj = 0) mtext(date(), side = 1, line =.5, cex = 0.7, outer = T, adj = 1)
Assignment 4-2Script
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 24
Learn R Toolkit
Assignment 4-3Make Step Chart and Scatter Plot
Interactively Edit Your Practice_4_1_xy_plot.R Script to make these charts
type = ‘s” type = ‘p”
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 25
Learn R Toolkit
Working With TextMenu
Text is Critical for chart interpretation
Click video image to start video
D Kelly O'Day R Charts Mod 4 - R Charts: 26
Learn R Toolkit
Working With Text
• Text Additions:
– main= argument to add chart title in figure margin at top
– sub= argument to add subtitle below X axis
– text() – low level function to add text in plot area
– mtext() – low level function to add text in margin and outer areas
• Size: par(ps=10)
• Magnification: cex = 0.85• Color: col=“red” (657 color choices)
• font= 1-4 (regular, bold, italic, bold italic)
• family= (“sans”, “serif”, “mono”)• Alignment: adj = 0,.5,1(left,center, right)
• Rotation: srt=
Menu
Text is Critical for chart interpretation
D Kelly O'Day R Charts Mod 4 - R Charts: 27
Learn R Toolkit
Adding text string in Plot Areatext () Function
text( x, y, “note”, pos =0 , cex = 1, col = “red”, srt = 45)
x,y – plot area coordinates where text should be placed
“note” – text to be added to plot pos – position of text with respect to
x, y coordinates. Default is centered on point.
cex - font magnification factor col - color srt – text rotation - degrees
Menu
• User can construct multi-line text strings by using \n to designate new line
• Note <- “This is an example \n of a multi-line note ”
\n for Multi-line Text
\”to add quote marks to text string
• Text strings designated by “ “ marks• User can embed quote marks within text
string by using \” to have R not treat mark as begin/end of text string
• Note <- “This is an example of
using \”quote marks\” within text string”
D Kelly O'Day R Charts Mod 4 - R Charts: 28
Learn R Toolkit
Simple Plot – No Annotation
#################### Example R Script: ################# Ex_Scr_4_4_simple_plot.R ##########################Script to read data file, simple plot ## STEP 1: SETUP - Source File rm(list=ls()); oldpar<- par(no.readonly=T); ;par(las=1)link <- "C:\\Learn_R\\Mod_4_R_Charts\\Data_4_1_GISS_1980_By_year.txt.txt"
## STEP 2: READ DATA my_data <- read.table(link, skip =0, sep = ",", dec=".", row.names = NULL , header = F, colClasses = c("numeric","numeric"), comment.char = "#", na.strings = c( "","*", "-",-99.9, -999.9 ), col.names = c( "yr", "anom") ) attach(my_data)## STEP 3: MANIPULATE DATA## STEP 4: PRODUCE PLOT - REPORT plot(yr, anom, type = "l", col = "red")## Outer margin annotation my_date <- format(Sys.time(), "%m/%d/%y") mtext(script, side = 1, line = .5, cex=0.7, outer = T, adj = 0) mtext(my_date, side = 1, line =.5, cex = 0.7, outer = T, adj = 1)## STEP 5: CLOSE par(oldpar) detach(my_data)
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 29
Learn R Toolkit
Simple Plot –with Annotation
#################### Example R Script: ################# Ex_Scr_4_5_simple_plot_w_annotation.R ######################## ##Script to read data file, simple plot ## STEP 1: SETUP - Source File rm(list=ls()) script<- "C:\\Learn_R\\Mod_4_R_Charts\\Ex_Scr_4_5_simple_plot_w_annotation.R" oldpar<- par(no.readonly=T) par(oma=c(2,2,1,2)); par(las=1); par(mar=c(5,4,2,1)) link <- "C:\\Learn_R\\Mod_4_R_Charts\\Data_4_1_GISS_1980_By_year.txt.txt"## STEP 2: READ DATA my_data <- read.table(link, skip =0, sep = ",", dec=".", row.names = NULL , header = F, colClasses = c("numeric","numeric"), comment.char = "#", na.strings = c( "","*", "-",-99.9, -999.9 ), col.names = c( "yr", "anom") ) attach(my_data)## STEP 3: MANIPULATE DATA m_title <- "GISS Temperature Anomaly - C (1980-2008)" sub_title <- "Source: http://data.giss.nasa.gov/gistemp/" note <- "Baseline 1951-1980"## STEP 4: PRODUCE PLOT - REPORT plot(yr, anom, type = "l", col = "red", main = m_title, sub = sub_title, ylab = " Temperature Anomaly - C", xlab = "", cex.axis = 0.75, cex.lab=0.8, cex.main = .8, cex.sub = 0.6) text(1985,0.65, note, cex=0.6 ) my_date <- format(Sys.time(),"%m/%d/%y") mtext(script, side=1, line = .5, outer = T, adj = 0, cex = 0.65) mtext(my_date, side = 1, line = 0.5, outer = T, adj = 1, cex = 0.7)## STEP 5: CLOSE par(oldpar); detach(my_data)
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 30
Learn R Toolkit
text()font & family
• font= font type for plot text=1 Standard =2 Bold=3 Italic=4 Bold and italic
• Use for other figure text– font.axis; font.lab– font.main; font.sub
• family = controls font family
= “sans”
= “serif”
= “mono”
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 31
Learn R Toolkit
paste() Functionconcatenates arguments into a single string
paste(arg1, arg2, arg3, sep= “ ”)
arg1 – text string or variable to be concatenated with other arguments
sep = “ ” - separator to add between arguments. Space good for text.
Variable data and text strings can be
concatenated into a single string that can
then be added to plot with text()
Example:
# build text string with paste()
my_date <- paste(“today is “, date())
# add text string to plot
text(x, y, my_date, col = “red”)
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 32
Learn R Toolkit
Adding Text within Margin Area
mtext( “note”, side = , line = , outer = F, adj = 0, cex = 1, col = “red”)
• “note” – text to be added to margin area
• side – side of plot to place text(1= bottom, 2= left, 3= top, 4=right)
• line – line of margin to place text, starting at 0, counting outwards
• outer – use outer area (T or F)
• adj – text alignment, 0 = left, 0.5= center, 1 = right
• cex - font adjustment factor
• col - color
Menu
1
2
3
4AxisSides
Axis Numbering Convention
D Kelly O'Day R Charts Mod 4 - R Charts: 33
Learn R Toolkit
How I’ve Been Adding Margin Text to Each Mod 4 Plot
3 Steps to Create Margin Annotation:
• Set Outer Margin Areas
par(oma=c(2,2,0,1))
• Establish script name vector
script<- "C:\\Learn_R\\Mod_4_R_Charts\\Ex__plot_.R"
• Develop Margin Text w/date & script name
## Outer margin annotation my_date <- format(Sys.time(), "%m/%d/%y") mtext(script, side = 1, line = .5, cex=0.7, outer = T, adj = 0) mtext(my_date, side = 1, line =.5, cex = 0.7, outer = T, adj = 1)
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 34
Learn R Toolkit
Assignment 4-4Annotate Simple Chart Yourself
• Start R Session
• In R Console, Open Script:“C:/Learn_R/Mod_4_R_Script/
Ex_Scr_4_3_simple_plot.R”
• Save as:“C:/Learn_R/Mod_4_R_Script/Practice_4_2_my_simple.R”
• You’ve seen me do it
• Make the Full Annotation on your own
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 35
Learn R Toolkit
Adding Lines in Plot AreaMenu
Click video image to start video
D Kelly O'Day R Charts Mod 4 - R Charts: 36
Learn R Toolkit
Adding Lines in Plot AreaMenu
#################### Example R Script: ################# Ex_Scr_4_6_add_lines_to_plot.R ##########################Script to read data file, simple plot no annotation ## STEP 1: SETUP - Source File rm(list=ls()) script<- "C:/Learn_R/Mod_4_R_Charts/Ex_Scr_4_6_add_lines_to_plot.R"
oldpar<- par(no.readonly=T) ; par(las=1) par(ps=10); par(oma=c(2,2,1,2)) ## STEP 2: READ DATAx <- 0:100; y <- x^2x_pts <- c(15, 35, 35, 15, 15); y_pts <- c(8300, 8300, 6500, 6500,8300)# STEP 3: MANIPULATE DATA# STEP 4: PRODUCE CHART - REPORTplot(x,y, type = "n“ , main="Add Lines, Points, Arrows Examples")
points(x, y,col = "black", lty=1, type = "l")grid(col="lightgrey", lty=1)abline(h=2500, col="red")abline(v=50, col = "blue")arrows(65,8400, 85,8400, code=3, col="orange", length = 0.1)lines(x_pts, y_pts, lty=1, col = "green")points(x_pts,y_pts, type = "p",col ="red",pch=19)
my_date <- format(Sys.time(),"%m/%d/%y") mtext(script, side=1, line = .5, outer = T, adj = 0, cex = 0.65) mtext(my_date, side = 1, line = 0.5, outer = T, adj = 1, cex = 0.7)## STEP 5: CLOSE par(oldpar) detach(my_data)
D Kelly O'Day R Charts Mod 4 - R Charts: 37
Learn R Toolkit
Assignment 4-5Working with grid(), points(), abline(), arrows() & lines()
Menu
• Start R Session
• In R Console, Open Script:“C:/Learn_R/Mod_4_R_Script/Ex_Scr_4_6_add_lines_to_plot.R”
• Save as:“C:/Learn_R/Mod_4_R_Script/Practice_4_3_add_lines_to_plot.R”
• You’ve seen me work with it
• Changes each element to see what happens, get comfortable with forms of lines
Printout & Read R Documentation for lines
? grid()? points()? lines()? abline()? arrows()
D Kelly O'Day R Charts Mod 4 - R Charts: 38
Learn R Toolkit
Extra Scripts
Click video image to start video
Menu
D Kelly O'Day R Charts Mod 4 - R Charts: 39
Learn R Toolkit
Plot Box and Axis Styles
• Plot Box & Axis Options– Box type
• bty=“n”• bty=“o”
– Axes• axes = T or F
– Axis Offset: • xaxs= “i” or “r”• yaxs = “i” or “r”
– Axis 3 & 4 tick marks• Axis(n, ..tick=T)
Menu