Plots in R

Simple Plots in R


There are varieties of plots in R, lets try some of them
Simple scatter plot import data from sheet 2 of  demo data.xls,
read.table('clipboard',header=T) ->a.df
names (a.df)
attach(a.df)
a.df
plot (year,temp)                                # scatter plot
plot (year,pcpn)                        # scatter plot
There are different types of plots
Boxplot, Histogram, Bar plot, Line,......

Changing parameters in plot command
Now work with sheet 1 data in demodata.xls file
To plot in new window (keep the previous)
X11()                 # give new blank window to plot
# Notice comma (,) and inverted codes ('  ')
In about commands, the circled functions right side of '=' is changeable. 
Practice with sheet 2, demo data excel file
temp.df<- read.table ('clipboard', header=T)
attach (temp.df)
plot (year, temp, xlab='Year', ylab='Temperature', main='Annual Average Temperature', pch=18 , col='blue')
plot (year, temp, xlab='Year', ylab='Temperature',  main='Annual Average Temperature', type='s' , col='blue')
Practice changing the 'pch' values (eg. 15, 11, 21), colour (eg. yellow, red, green), type (eg. S, l, h, b)

Multiple chart in a window
par(mfrow=c(1,3))
par = the graphics parameter,
mfrow = mf (make fragment?)
row (number of rows),
c(nr, nc) = [c (concentrate or concatenate), nr =number for rows), c =number of columns)]
Subsequent figures will be drawn in an nr-by-nc array on the device by columns (mfcol), or rows (mfrow), respectively.
x<-0:10
x1<-0:15
x2<-0:20
par(mfrow=c(1,3))
boxplot(x,x1,x2)
barplot(x1,x2)
plot(x)
Defining graphical parameters
par(mfrow=c(1,3), bg='gray’)   # bg= Background Colour
par(mfrow=c(1,3), bg='light yellow', cex=.8)       # cex= define font size, but it doesn’t match with mother programmes as here font size is relative
par(bg='green', cex=.8, mar=c(4,3,2,2))              # mar= margin, it goes clockwise from bottom, left, top and right












Plot and Legends
Legend components

















Creating vector for Matplot
y60<-c(316.27, 316.81, 317.42, 318.87, 319.87, 319.43, 318.01, 315.74, 314.00, 313.68, 314.84, 316.03)
y70<-c(324.89, 325.82, 326.77, 327.97, 327.91, 327.50, 326.18, 324.53, 322.93, 322.90, 323.85, 324.96)
y80<-c(337.84, 338.19, 339.91, 340.60, 341.29, 341.00, 339.39, 337.43, 335.72, 335.84, 336.93, 338.04)
y90<-c(353.50, 354.55, 355.23, 356.04, 357.00, 356.07, 354.67, 352.76, 350.82, 351.04, 352.69, 354.07)

CO2<-data.frame (y60, y70, y80, y90)                    # making matrix from 4 vectors
CO2                                                                                                    # there is no row names
row.names(CO2)<-c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") # adding row names
CO2
row.names(CO2)                                                                            # check values
matplot(CO2)                                                                           # mat plot
Note: here the observations labeled '1' represents the monthly CO2 levels for 1960, '2' represents those for 1970, and so on.
colnames(CO2) <- c("1960", "1970", '1980','1990')
CO2



We can enhance the plot by changing the line types and adding axis labels and titles:
x11()
matplot(CO2,axes=F, frame=T, type='b', ylab="", col=1:4)
    #axes =F:                               Initially do not draw axis, try changing F and T
    #frame =T:                             Box around the plot is drawn; try changing F instead T
    #type =b:                               Both line and character represent a seris;
    #ylab ="":                               No label for y-axis is shown;
    #ylim =c(310,400):                Specify the y-axis range
    #col =1:4                               Is define colors from colour 1 to 4, try changing it
axis(2)                                # put numerical annotations at the tick marks in y-axis;
axis(1, 1:12, row.names(CO2))
    # use the Monthly names for the tickmarks in x-axis; length is 12;
title(xlab="Month")                       #label for x-axis;
title(ylab="CO2 (ppm)")     #label for y-axis;
title("Monthly CO2 Concentration \n for 1960, 1970, 1980 and 1990")                      # '\n' is line break (like enter)
legend('topleft',c('1960','1970','1980','1990'),pch=c('1','2','3','4'),col=1:4,bty='o')

Try changing different parameters by yourself.

Pie chart
piechart<-read.table('E:R Exercise/R class/piedata.txt',header=T)
piechart
attach(piechart)
pie(score, label=rank, clockwise=TRUE, col= c("red", "orange", "yellow", "green", "blue", "purple"),  border=NA)
title(main="Clockwise Pie Chart with custom colours", font.main= 4)

Matplot
Plot the columns of one matrix against the columns of another
a<-seq(1:10)
b<-seq(10:1)
c<-seq(1:10)^2
matplot(a,b,type='l', lwd=1)
matplot(a,c)
matpoints(a, b, type = "p")
matlines (a, b, type = "l",lwd=3)
matlines (a, c, type = "l")



High Quality plot export
tiff(filename = "D:/pie.tiff", pointsize=7, width = 8.5, height = 8.5,units = "cm", res = 400, restoreConsole = TRUE)   # to starting graphics command, filename = the drive/folder location and the desired file name, with extenstion
The command 'tiff' can be jpeg, ping, pdf but you need to change the parameters in in parenthesis 
pie(score, label=rank, clockwise=TRUE, col= c("red", "orange", "yellow", "green", "blue", "purple"),  border=NA) # you can give any type of plots you want
dev.off()                 # to end graphics command, then the plot will be saved in above given location



Working with plot and legends
data.df<-read.table('E:/R Exercise/R class/regression.txt', header=T)
data.df; names(data.df); attach(data.df)
par(mfrow = c(1,1), col='green', bg='6', col.axis='red', col.lab= 'white', fg='blue') # setting different parameters in 'par' command
here,       col =                        colour of plot (eg points in plot)
              bg =                         background colour
              col.axis =                 colour of axis
              col.lab =                   colour of axis labels
              fg =                          foreground label                                    
It is not necessary to state if you want to plot only one plot in a plot window
plot(growth, pch=20, col='yellow')                                         
Plot for only one variable
lines(growth,lty=3, col=3)
lines(lowess(growth), col=2, lty=2,lwd=2)
Find help file for more on 'lowess', it a kind of polynomial regression
legend(5.5,12, c('growth', 'Line join', 'Polynomial regression'),
       lty=c(0,3,1),col=c(1,3,2),pch=c(20,NA,NA))
Try with more parameters and changed location of legend
legend('topright',c('growth','Line join', 'Polynomial regression'), pch=c(20,NA,NA), lty=c(0,3,1), col=c(1,3,2), bty='n',cex=0.8)

# 0.9, 4                                  - position of top left corner or legend to place
# bottomright                          - is position of legend
# c('growth','Line join', 'Polynomial regression') -text to describe legends
# pch=c(20,NA,NA)             - is to give legend types that are used in plot, hence must be the same as above command
# lty=c(0,3,1)                      - is line types that are used above in line command
# col=c(1,3,2)                     - colour types used in plot respectively to the commands
# bty=n                               - do not plot the legend box      
# cex=0.8                             - changes legend font size

Work yourself: add another variable 'tannin' and display in legend as well
points(tannin,pch=18)
legend('topright', c('growth', 'Line join', 'Polynomial regression', 'tannin'), pch=c(20,NA,NA,18),lty=c(0,3,1,0),col=c(1,3,2,1), bty='n')

Adding Text in plot
plot(growth, xlab='', ylab='',  type='n')       # here, type='n' means blank plot or nothing to display
mtext('Text on side 1, cex=1', side=1, cex=1)
mtext('Text on side 2, cex=1.2', side=2,cex=1.2)
mtext('Text on side 3, cex=1.3', side=3,cex=1.5)
mtext('Text on side 4, cex=2', side=4,cex=2)
text(5,5, "TESTING")
text(5,10,'CHEKCING')

Adding symbols to plots
abline()                                                        # can be used to draw a straight line to a plot.
abline(a,b)                                        # a= y-intercept, b=slope.
plot(growth,xlim=c(0,25),ylim=c(0,30))
abline(h=30, lwd=2)                         # draws a horizontal line at y=30.
abline(v=12)                                    # draws a vertical line at x=12.
abline(h=12,lwd=3)
abline(v=4,lty=5)

let's try with changing parameters
plot(growth,tannin)
abline(a=3,b=.2)
abline(v=5)
plot(growth)
abline(a=2,b=.3)

Adding arrow and line segment
plot(growth, tannin)
arrows(5,2,6,4)                                      # (start.x,start.y, end.x,end.y)
segments(5,2,10,1,lty=3)                        # (start.x,start.y, end.x,end.y)
title("arrow and segment")     
text(6,4.2,"This the point", cex=0.7)

Identifying plotted points
# While examining a plot, identifying a data point such as possible outliers can be achieved using identify() function.
plot(growth,pch=16,col=2,cex=2)                   # pch= point type, col= colour type, cex = size
identify(data.df$growth, n=8)          # work for single variable plot only

# After pressing return, R waits for you to identify (n=8) points with the mouse.
# Moving the mouse cursor over the graphics window and click on a data point.
# Then the observation number appears next to the point, thus making the point identifiable.

No comments:

Post a Comment