Statistical Programming with R

Similar documents
IST 3108 Data Analysis and Graphics Using R Week 9

Plotting Complex Figures Using R. Simon Andrews v

Intro to R Graphics Center for Social Science Computation and Research, 2010 Stephanie Lee, Dept of Sociology, University of Washington

Graphics - Part III: Basic Graphics Continued

R Workshop Module 3: Plotting Data Katherine Thompson Department of Statistics, University of Kentucky

AA BB CC DD EE. Introduction to Graphics in R

CIND123 Module 6.2 Screen Capture

INTRODUCTION TO R. Basic Graphics

Data Visualization. Andrew Jaffe Instructor

Using Built-in Plotting Functions

Types of Plotting Functions. Managing graphics devices. Further High-level Plotting Functions. The plot() Function

Package areaplot. October 18, 2017

Graphics in R Ira Sharenow January 2, 2019

Graphics in R STAT 133. Gaston Sanchez. Department of Statistics, UC Berkeley

Introduction to R. Biostatistics 615/815 Lecture 23

Statistics 251: Statistical Methods

Error-Bar Charts from Summary Data

Az R adatelemzési nyelv

DSCI 325: Handout 18 Introduction to Graphics in R

Advanced Graphics with R

Statistical Programming Camp: An Introduction to R

An Introduction to R 2.2 Statistical graphics

Module 10. Data Visualization. Andrew Jaffe Instructor

STATISTICS: AN INTRODUCTION USING R. By M.J. Crawley. Exercises 1. PLOTS: GRAPHICAL METHODS OF DATA EXPLORATION

Advanced Econometric Methods EMET3011/8014

Basics of Plotting Data

Package EnQuireR. R topics documented: February 19, Type Package Title A package dedicated to questionnaires Version 0.

Introduction to RStudio

Plotting: An Iterative Process

The Basics of Plotting in R

Bar Charts and Frequency Distributions

BIMM-143: INTRODUCTION TO BIOINFORMATICS (Lecture 5)

Package visualizationtools

Graphics #1. R Graphics Fundamentals & Scatter Plots

An Introduction to R Graphics with examples

Recap From Last Time: Today s Learning Goals. Today s Learning Goals BIMM 143. Data visualization with R. Lecture 5. Barry Grant

Configuring Figure Regions with prepplot Ulrike Grömping 03 April 2018

Lab 1 Introduction to R

Excel R Tips. is used for multiplication. + is used for addition. is used for subtraction. / is used for division

GS Analysis of Microarray Data

R Graphics. Feng Li School of Statistics and Mathematics Central University of Finance and Economics

An Introduction to R Graphics

Continuous-time stochastic simulation of epidemics in R

Combo Charts. Chapter 145. Introduction. Data Structure. Procedure Options

Exploratory Data Analysis - Part 2 September 8, 2005

Part I - WORKING WITH ABSOLUTE REFERENCES

R Graph Essentials. Use R's powerful graphing capabilities to design and create professional-level graphics. David Alexander Lillis

Package arphit. March 28, 2019

plot(seq(0,10,1), seq(0,10,1), main = "the Title", xlim=c(1,20), ylim=c(1,20), col="darkblue");

R Graphics. Paul Murrell. The University of Auckland. R Graphics p.1/47

Introduction to R 21/11/2016

Package pwrrasch. R topics documented: September 28, Type Package

Introduction to Plot.ly: Customizing a Stacked Bar Chart

This document is designed to get you started with using R

Making plots in R [things I wish someone told me when I started grad school]

Lastly, in case you don t already know this, and don t have Excel on your computers, you can get it for free through IT s website under software.

Package SCBmeanfd. December 27, 2016

Package Grid2Polygons

Statistical Programming with R

Introduction to R for Beginners, Level II. Jeon Lee Bio-Informatics Core Facility (BICF), UTSW

Exploratory Projection Pursuit

Package Calculator.LR.FNs

Introduction Basics Simple Statistics Graphics. Using R for Data Analysis and Graphics. 4. Graphics

The first one will centre the data and ensure unit variance (i.e. sphere the data):

Introduction to R for Epidemiologists

Fathom Dynamic Data TM Version 2 Specifications

Chapter 5 An Introduction to Basic Plotting Tools

Assignments. Math 338 Lab 1: Introduction to R. Atoms, Vectors and Matrices

Package sciplot. February 15, 2013

EXCEL 2003 DISCLAIMER:

Stat 290: Lab 2. Introduction to R/S-Plus

Dr. Junchao Xia Center of Biophysics and Computational Biology. Fall /6/ /13

Topics for today Input / Output Using data frames Mathematics with vectors and matrices Summary statistics Basic graphics

Chapter 2: Descriptive Statistics: Tabular and Graphical Methods

HOUR 12. Adding a Chart

Univariate Data - 2. Numeric Summaries

Creating a Basic Chart in Excel 2007

Graph tool instructions and R code

Math 121 Project 4: Graphs

Introduction to R: Day 2 September 20, 2017

An introduction to WS 2015/2016

LECTURE NOTES FOR ECO231 COMPUTER APPLICATIONS I. Part Two. Introduction to R Programming. RStudio. November Written by. N.

FlowJo Software Lecture Outline:

Install RStudio from - use the standard installation.

R is a programming language of a higher-level Constantly increasing amount of packages (new research) Free of charge Website:

0 Graphical Analysis Use of Excel

Package desplot. R topics documented: April 3, 2018

The nor1mix Package. August 3, 2006

LAB #1: DESCRIPTIVE STATISTICS WITH R

From Getting Started with the Graph Template Language in SAS. Full book available for purchase here.

> glucose = c(81, 85, 93, 93, 99, 76, 75, 84, 78, 84, 81, 82, 89, + 81, 96, 82, 74, 70, 84, 86, 80, 70, 131, 75, 88, 102, 115, + 89, 82, 79, 106)

Make sure to keep all graphs in same excel file as your measures.

Statistical Software Camp: Introduction to R

Desktop Studio: Charts. Version: 7.3

The LDheatmap Package

A Handbook of Statistical Analyses Using R. Brian S. Everitt and Torsten Hothorn

Microsoft Excel 2000 Charts

Practical 2: Plotting

Visualizing in R advanced plotting

Package qrfactor. February 20, 2015

Transcription:

Statistical Programming with R Lecture 9: Basic graphics in R Part 2 Bisher M. Iqelan biqelan@iugaza.edu.ps Department of Mathematics, Faculty of Science, The Islamic University of Gaza 2017-2018, Semester 1

barplot() function The barplot() command creates bar charts. The bars can be drawn as vertical or horizontal. Example: ## Make values for basic barplot > rain = c(34, 32, 23, 15, 10, 8, 6, 9, 12, 21, 24, 29) > month = month.abb[1:12] # Make labels ## Now draw the plot ## Increase y-axis limits and add titles > barplot(rain, ylim = c(0, 35), names = month, main = "Rainfall", xlab = "Month", ylab = "Rainfall in mm") # las=3 is an option to make the labels perpindicular # > grid(ny = 35, nx = 0) to make horizontal lines (net) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 1 / 34

barplot() Graph Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 2 / 34

Example 2: Horizontal bar charts ## More data, this time as a matrix > data(vadeaths) # Data are in R datasets ## Now draw stacked bar chart with horizontal bars ## Note that xlab annotates bottom axis ## There is no legend automatically > barplot(vadeaths, xlab = "Deaths per 1000", horiz = TRUE) ## Add main title afterwards > title(main = "Death Rates in Virginia (1940)") Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 3 / 34

Horizontal bar charts graph Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 4 / 34

A bar chart with adjacent (grouped) bars and a legend Example: ## Same data as previous - a Matrix > data(vadeaths) # Data are in R datasets ## Draw bar chart with adjacent bars ## Add a legend. Note parameters passed to legend command > barplot(vadeaths, beside = TRUE, legend = TRUE, args.legend = list(bty = "n", title = "Age category")) ## Add titles afterwards > title(ylab = "Deaths per 1000", xlab = "Category") Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 5 / 34

A bar chart with adjacent (grouped) bars and a legend Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 6 / 34

Legend A legend can be added via the legend() function. It can produce a legend on a plot, displaying points or lines with accompanying text. The function accepts x= and y= arguments to specify the coordinates where the legend should be placed. Otherwise, you can specify x and y coordinates using a text string. The text options are bottomright, bottom, bottomleft, left, topleft, top, topright, right, and center. A legend= argument with the text to appear in the legend. Usually this will be a character or expression vector. Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 7 / 34

Examples: A Legend To A Plot More Options ## Make an empty plot to create a coordinate system plot(0:10, 0:10, type = "n") ## Add some points/lines points(3:5,4:6,type="b",lwd=2,lty=1,pch=21,col="black") points(2:4,2:4,type="b",lwd=2,lty=2,pch=24,col="blue") points(5:7,5:7,type="b",lwd=2,lty=3,pch=25,col="red") ## Make a list of names as labels for each set ## of lines/points mydata = c("line1", "Line2", "Line3") ## Add a legend, take care to match up line/point ## parameters legend("topright", legend = mydata, lty = 1:3, lwd = 2, col = c("black", "red", "blue"), pch = c(21, 24, 25)) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 8 / 34

A Legend To A Plot More Options: Graph Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 9 / 34

Examples: Continue... ## It is often easier to make named objects for colors ## and plot characters plcols = c("black", "red", "blue") plchr = c(21, 24, 25) ## Add more legends: note the various options legend("bottomleft", legend=mydata, lty = 1:3,col = plcols, pch = plchr, bty = "n", title = "Sample\nLegend Title") ## One line legend box legend("top", legend = mydata, lty = 1:3, col = plcols, pch = plchr, horiz = TRUE, inset = 0.01) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 10 / 34

A Legend To A Plot More Options: Graph Continue... Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 11 / 34

Examples: Continue... ## numeric coordinates for legend box legend(8.2, 1.7, legend = mydata, lty = 1:3, col = plcols, pch = plchr, bg = "gray90") ## Two-column legend box legend("right", legend = mydata, lty = 1:3, col = plcols, pch=plchr, ncol=2, inset=0.01, title = "Two-column Layout") ## This time go for simple colored boxes legend(0, 8, legend = mydata, fill = plcols) ## Add a legend using the mouse to set the location ## Top left of legend appears where you click with the ## mouse legend(locator(1), legend= mydata, lty= 1:3,col = plcols) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 12 / 34

A Legend To A Plot More Options: Graph Continue... Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 13 / 34

Two-dimensional gure: scatterplot (plot) plot(cars$dist,col=2,pch=16,cex=1.4,xlab="cars",ylab="frequenc points(cars$speed,col=3,cex=1.5) legend("topleft",c("dist.","speed"),pch=c(16,1), col=c(2,3),bg="gray90") title(main="speed and Stopping Distances of Cars") Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 14 / 34

Histograms (plot) hist(): This command creates histograms. The command computes the required values before plotting the histogram. Example: ## Make some data set.seed(99) # Set random number generator dat = rnorm(50, mean = 10, sd = 1.5) ## Draw histogram ## Extend x-axis limits, add density ## fill lines hist(dat, xlim = c(4, 14), density = 15, angle = 60) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 15 / 34

Histogram of Random Normal Data plot Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 16 / 34

Two-Added Histograms (plot) hist(cars$speed, xlim=c(0,150), ylim=c(0,35), breaks= seq(0,150,10), col="skyblue", ylab= "Frequency", border= "pink", xlab="cars Frequences", main="speed and Stopping Distances of Cars") hist(cars$dist,xlim=c(0,150),ylim=c(0,35), breaks=seq(0,150,10), add=t, density=9) legend(115,35,legend=c("speed","distance"), fill=c("skyblue","black"), density=c(na,9)) box() Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 17 / 34

Added Histograms plot Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 18 / 34

Density curve plotted over a histogram Sometimes it's useful to plot a density curve over a histogram to help identify the distribution, or demonstrate the deviation between sample distributions and proposed population distributions: RandomData <- rnorm(1000) hist(randomdata, freq=false, col="brown2") curve(dnorm, add=true, col="blue4", lwd=2);box() Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 19 / 34

Pie Charts A pie() function is used to plot a pie charts graph. Let's start with a simple pie chart graphing the books vector. Consider the books vector with 6 values. The values in books are displayed as the areas of pie slices. books <- c(2, 4, 7, 5, 8, 10) Create a pie chart for books pie(books) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 20 / 34

Pie Charts More Options As in a plot function, we can add many parameters to a pie function. Now let's add a heading, change the colors, and dene our own labels. pie(books, main="books", col=rainbow(length(books)), labels=c("mon","tue","wed","thu","fri","sat")) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 21 / 34

Pie Charts More Options Now let us change the colors, label using percentages, and create a legend. Create a vector of heating colors. Calculate the percentage for each day, and round each value to one decimal place. Combine a "%" sign after each value. Then create the pie chart plot using pie function. Finally, create a legend at the right side of the plot. colors <- heat.colors(length(books)) book_labels <- round(books/sum(books) * 100, 1) book_labels <- paste(book_labels, "%", sep="") pie(books, main="books", col=colors, labels=book_labels, cex=0.8) legend(1.5, 0.5, c("mon","tue","wed","thu","fri"), cex=0.8, fill=colors) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 22 / 34

Pie Charts Plot Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 23 / 34

Pie Charts Plot > pie(rep(1, 30), col = rainbow(30), radius = 0.9) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 24 / 34

Multiple Plots on a Page The default is to have one plot per window. If you would like more, you can use the following command: par(mfrow=c(, ))(multi-gure, by row) Within the c(, ), choose how many rows and columns of pictures you would like. If you have four plots, par(mfrow=c(2,2)) 2 rows and 2 columns If you have six plots, par(mfrow=c(2,3)) or par(mfrow=c(3,2)). If you have fewer plots than spaces on the window, R will just leave the others blank. However, if you want to go back to one plot per window, you need to reset to par(mfrow=c(1,1)). Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 25 / 34

## Set plot window into 6 (2 rows, 3 columns) opt = par(mfrow = c(2, 3)) ## Produce 6 color wheels as pie charts pie(rep(1,12), col = rainbow(12), radius = 0.95, main = "Rainbow Colors"); box(which = "figure") pie(rep(1,12), col = heat.colors(12), radius = 0.95, main = "Heat colors"); box(which = "figure") pie(rep(1,12), col = terrain.colors(12), radius = 0.95, main = "Terrain Colors"); box(which = "figure") pie(rep(1,12), col = topo.colors(12), radius = 0.95, main = "Topo Colors"); box(which = "figure") pie(rep(1,12), col = cm.colors(12), radius = 0.95, main = "CM Colors"); box(which = "figure") pie(rep(1,12),col = gray(seq(0,1,len=12)),radius = 0.95, main = "Gray Colors"); box(which = "figure") Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 26 / 34

Multi-Figure Mode Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 27 / 34

title(main = "Sine and Cosine functions") Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 28 / 34 plot() with curve() functions in one gure mode type: ## First of all reset to one figure mode type ## use par(mfrow=c(1,1)) or easily par(opt) ## Plot a trig function ## curve command would give same result ## Set x-axis to go from -2*pi to +2*pi plot(sin, from = -pi*2, to = pi*2, lty = 2, lwd = 3, ylim = c(-1, 1.5), ylab = "y-value") ## Plot the cosine, use curve command and set ## add = TRUE to overlay curve(cos, from = -pi*2, to = pi*2, lty = 3,lwd = 3,add=T) ## Add a legend, be careful to styles from the plot legend("topright", legend = c("sine", "Cosine"), lty = c(2, 3), lwd = c(3, 3), bty = "n") ## Give a main title

Multi-Figure Mode Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 29 / 34

More math. Expressions with text curve(2 * exp(-x/2), from = 0, to = 7, ylim = c(0, 2), xlab = "", ylab = "",col=5, lwd=3) curve(2 * exp(-x), add = TRUE, lty = 4, col=4, lwd=3) curve(x * exp(-x/2), add= TRUE, lty = 2, col=2, lwd=3) curve(2 * x * exp(-x/2),add= TRUE,lty = 3,col=3,lwd=3) text(0.4, 1.9, expression(paste("exponential: ", 2 * e^(-x/2))),col=5, adj = 0) text(4, 0.7, expression(paste("ricker: ", x * e^(-x/2))),col=2) text(4, 1.25, expression(paste("ricker: ", 2 * x * e^(-x/2))),col=3,adj = 0) text(2.8, 0.12, expression(paste("exponential: ", 2 * e^(-x))),col=4) title( expression(paste("exp plots: ", 2 * e^(-x/2), x * e^(-x/2), 2 * x * e^(-x/2),2 * e^(-x) ))) Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 30 / 34

Exponential plots with expressions Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 31 / 34

Device Drivers By default, a window will automatically be opened to display your graphics. Some other devices available include postscript(), pdf(), png() and jpeg(). (See the help for Devices for a complete list.) To use an alternative driver, either call the appropriate function before plotting, or use the dev.copy() function to specify a device to which to copy the current plot, always ending with a call to dev.off(). For example, to create a PostScript plot, use statements like postscript(file="myplot.ps")... plotting commands go here... dev.off() To create a jpeg image from the currently displayed plot, use dev.copy(device=jpeg,file="picture.jpg") dev.off() Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 32 / 34

4 Histograms plot saving postscript("4gammaplot.ps") x <- seq(0, 30, length=300) gshape <- c(2, 5, 10, 15) colors <- c("red", "blue", "darkgreen", "gold") plot.new() plot.window(xlim=c(0,30),ylim=c(0,0.4)) axis(1); axis(2) for (i in 1:4){ lines(x, dgamma(x,shape=gshape[i], scale=1), lwd=2, col=colors[i])} # Inserting mathematical expressions text(3.5,.35, expression(paste(alpha==2))) text(6.5,.18, expression(paste(alpha==5))) text(11.5,.13, expression(paste(alpha==10))) text(23,.05, expression(paste(alpha==15))) dev.off() Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 33 / 34

4 Gamma plot saving dev.copy(device=pdf,file="4gammaplot.pdf") dev.off() The Saved plot looks like: Bisher M. Iqelan (IUG) Lecture 9: Basic graphics in R Part 2 1 st Semester 2017 34 / 34

End of lecture 8 Part(2). Thank you.!!!