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