introduction to R: learning by doing (part 2: plots)
[This article was first published on geo-affine » R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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 "l"ine 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-axis", ylab = "y-axis", xlim = c(0,2), ylim = c(0,2) ) #to arrange the limits ...
Sometimes you will need several plots in one graphic. Here you go with the code:
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
But what is a graphic without storing it?
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
And here is our tester.pdf:
To leave a comment for the author, please follow the link and comment on their blog: geo-affine » R.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.