# introduction to R: learning by doing (part 2: plots)

Lets go one with the second part of learning R by doing R (you will find the first part here. As we have used vectors, matrices and loops in the first part, we will concentrate on graphics in this one. but first we will need data to plot:

x <- vector(,10) #will create an empty vector with length 10 y <- vector(,10) z <- vector(,10) for (i in c(1:10)) { x[i] <- i/10 y[i] <- x[i]^2 z[i] <- sqrt(x[i]) } plot(y~x) #will create a plot with values of x on the x-axis and values of y on the y-axis plot(y~x, type='l', col='red') #to get a line in red help(plot) #see what other line types there are. title(main="example quadr. function") #to set a title plot(y~x, type = 'l', col = 'red', main = "example quadr. function") #will make more or less the same plot(y~x, type = 'l', col = 'red', main = "example quadr. function", xlab ="x-axis";, ylab="y-axis") #to add non-standard labels for the axis plot(y~x, type = 'l', col = 'red', main = "example quadr. function", xlab = "x-axi";, ylab ="y-axis", xlim = c(0,2), ylim = c(0,2) ) #to arrange the limits ... [/sourcecode] Sometimes you will need several plots in one graphic. Here you go with the code: [sourcecode language="r"] par(mfrow=c(2,2)) #to create a canvas for 2x2 plots plot(y~x) plot(y~z, main="a little plot") plot(z~x) par(oma=c(0,0,2,0)) #for creating a title for the whole subplot. c(0,0,2,0) defines the location check help(par) for help on the "oma" parameter title(main="my first multi-plot", outer=T) #to create a title on the outer frame [/sourcecode] But what is a graphic without storing it? [sourcecode language="r"] pdf("tester.pdf") #create a file in your curent working directory par(mfrow=c(2,2)) #to create a canvas for 2x2 plots plot(y~x) plot(y~z, main="a little plot") plot(z~x) par(oma=c(0,0,2,0)) #for creating a title for the whole subplot. c(0,0,2,0) defines the location check help(par) for help on the "oma" parameter title(main="my first multi-plot", outer=T) dev.off() #will close the file dir(getwd()) #should list your pdf file ðŸ˜‰ [/sourcecode] And here is our tester.pdf: