Monday, January 26, 2015

Oil Prices - Part II

This post is a continuation of  the blog post i wrote on Jan 14, 2015 - oil . I did not feel like explaining all the R code i used in one place and felt that it would be easier to learn how the plot was generated if it is broken into 3 parts. The first part is the entire image generated on Jan 14, 2015. The second part will elaborate on the R functions plot(), points(), lines() and ablines(). The third part will dig into the generating the custom axis.

So lets get started...

We have already discussed the method to import the data and generate a blank plot using the read.csv() and plot() functions in part one of the series on oil. We construct our plot on top of this blank plot. We would like to add gridlines which can be added to the plot using the abline() function. Since we require the plot to have horizontal and vertical lines we use both the v= and h= as arguments in the abline() function. The lty argument is used to specify the line type, readers can choose between 0 to 6 as lty. We chose 3 to specify ".". To learn more on the abline() function type ?abline in R console window. To learn about all the possible values type ?par in R console window. The lwd argument is the line width.

setwd("")
embargo=read.csv("oils.csv")
par(mar = c(5,7,5,7))
plot(embargo$percapita,embargo$price, type ="n",axes = FALSE,xlab = NA,ylab =NA)
abline(v= c(7000,8000,9000), h = c(25,50,75,100),lty = 3,lwd = 1.5)

Once we generate the grid we can construct our plot. We have added two additional lines of code - the lines() function and the points() function.R will plot the lines before plotting the points. If we are interested in displaying the line over the points we can just change the order of the two function.
par(mar = c(5,7,5,7))
plot(embargo$percapita,embargo$price, type ="n",axes = FALSE,xlab = NA,ylab =NA)
abline(v= c(7000,8000,9000), h = c(25,50,75,100),lty = 3,lwd = 1.5)
lines(embargo$percapita,embargo$price, lwd = 2, col = "#28363F")
points(embargo$percapita,embargo$price, lwd = 2, pch = 21, bg = "white", col ="#28363F", cex = 1.5)

The initial two arguments in the lines() function are the data points to be displayed on the Xaxis and Yaxis.The lines() function will simply join the points with a smooth line. The points() function has exactly the same arguments. The cex argument allows us to control the size of the points displayed.

No comments:

Post a Comment