SlideShare a Scribd company logo
Abhik Seal: Scatter plots in R


I have taken a sample from the Diamonds data from ggplot2 package

>sample1<-diamonds[sample(nrow(diamonds),400),]


>plot(sample1$price~sample1$carat,#Y~X
main = "Relation of diamonds price and carat",# Title
xlab ="Price",ylab = "carat",# X and Y label
xaxis="i",yaxis="i",# set axis style as internal
col ="red",# Color of the dots
pch=16)#Set the plotting symbol to filled dots

The pch attribute is changed to 2 a different symbol is noticed in figure 2.




             Fig 1                                        Fig 2

To set the plot background color to gray we use the bgargument in the par() command

>par(bg = “gray”)

Then running the plot code you will get something like in fig 3. In par() until the plotting device is closed or a
new device is initiated, the background color stays the same.
To set the background color for a the plot region a rectangle must be drawn around the plot region figure 4 The
script is given below.
    plot(sample1$price~sample1$carat,type="n") # "n" so that the plotted elements are invisible.
    x<-par("usr") #gets us the co-ordinates of the plot region in a vector of form c(xleft, xright, ybottom, ytop)
    rect(x[1],x[3],x[2],x[4],col="gray ")
points(plot(sample1$price~sample1$carat,pch=10)
Fig 3                                                    Fig 4
  If you want to make the title as red, axis values as blue and axis labels as red then you can do this figure 5

plot(sample1$price~sample1$carat,#Y~X
main = "Relation of diamonds price and carat",# Title
xlab ="Price",ylab = "carat",# X and Y label
xaxis="i",yaxis="i",# set axis style as internal
col.main ="red",# Color of the dots
col.axis="blue",
col.lab="red",pch=16)




Plotting point, symbols, styles and sizes

 I used this data (http://www.imdpune.gov.in/ncc_rept/RESEARCH%20REPORT%202.pdf ) from the year 1999 to
2003 and the months from jan to December to plot yearly rainfall.

NB: Columns are years and rows are months.

Here is the code
plot(rain$Year1999 ,main="Yearly Rainfall in India",xlab="Month of the Year",ylab="rainfall",pch=1)
points(rain$Year2000,pch=2)
points(rain$Year2001,pch=3)
points(rain$Year2002,pch=4)
points(rain$Year2003,pch=5)
legend('top',legend=c("1999","2000","2001","2002","2003"),ncol=5,cex=0.9,bty="n",pch=1:5)

Lines format can also be plotted using the lty and lwd arguments in the plot
plot(rain$Year1999
,main="Yearly Rainfall in India",xlab="Month of the Year",ylab="rainfall(mm)",type="l",lty=1,lwd=2,ylim=c(0,400))
lines(rain$Year2000,lty=2,lwd=2)
lines(rain$Year2001,lty=3,lwd=2)
lines(rain$Year2002,lty=4,lwd=2)
lines(rain$Year2003,lty=5,lwd=2)
legend('topright',legend=c("1999","2000","2001","2002","2003"),ncol=5,cex=0.9,bty="n",lty=1:5,lwd=2)
Lines type code:

      0: blank
      1: solid (default)
      2: dashed
      3: dotted
  4: dotdash
  5: longdash
6: twodash

axis(1,at=1:length(rain$Month),labels=rain$Month)
lines(rain$Year2000,col="red",type="b",lwd=2)
lines(rain$Year2001,col="orange",type="b",lwd=2)
lines(rain$Year2002,col="purple",type="b",lwd=2)
lines(rain$Year2003,col="yellow",type="b",lwd=2)
legend('topright',legend=c("1999","2000","2001","2002","2003"),col=
c("black","red","orange","purple","yellow"),ncol=2,cex=0.9,bty="n",lty=1:5,lwd=2)




Using xyplot to plot data.

I have used the sample1 data from the diamonds dataset . You also require the lattice package for plotting.You can
also plot high quality plots using ggplot see my qplot tutorial at slideshare.

xyplot(price~carat,data=sample1,groups=color,auto.key=list(corner=c(1,1)))

The auto.key use to make a legend at the corner of the plot.
Fitting linear model lines using lm() and abline()

plot(sample1$price~sample1$carat)
lmfit<-lm(sample1$price~sample1$carat)
abline(lmfit,col='red')
legend("topright", bty="n", legend=paste("R2 is", format(summary(lmfit)$adj.r.squared, digits=4)))# putting the
R square in the plot.




library(scatterplot3d)
scatterplot3d(x=sample1$carat,y=sample1$depth,z=sample1$price,xlab="carat",ylab="depth",zlab="price")#fig
scatterplot3d(x=sample1$carat,y=sample1$depth,z=sample1$price,xlab="carat",ylab="depth",zlab="price",pch
=16,highlight.3d=TRUE,angle=45,type="h")
More on the scatterplot3d at http://www.jstatsoft.org/v08/i11/paper


>plot(sample1$price~sample1$carat)
>rug(sample1$carat)
>rug(sample1$price,side=2,col="blue",ticksize=0.02)

     The rug function adds a set of lines just above the x and y axis.The closely packed lines represent
     the density of the data.The side argument takes four values,1: bottom axis (default) ,2: left ,3: top ,4:
     right.The size of the tick marks are adjusted by ticksize.




 smoothScatter :smoothScatter() function produces a smoothed color density representation of the
 scatter plot, obtained through a kernel density estimate.




 Lab.palette<-colorRampPalette(c("blue","red"), space = "Lab")
 smoothScatter(sample1$price~sample1$carat,colramp = Lab.palette)

More Related Content

DOCX
Plot3D Package and Example in R.-Data visualizat,on
KEY
Proga 0608
PPTX
Gauss in java
PDF
Py lecture5 python plots
PDF
Proga 0601
PPTX
KEY
Proga 0518
PPTX
Mat lab lecture part 1
Plot3D Package and Example in R.-Data visualizat,on
Proga 0608
Gauss in java
Py lecture5 python plots
Proga 0601
Proga 0518
Mat lab lecture part 1

What's hot (20)

PDF
Numpy python cheat_sheet
KEY
Kwp2 091217
PDF
NumPy Refresher
PDF
Basics of Computer graphics lab
PDF
Julia Set
PPT
Lecture on graphics
DOCX
Surface3d in R and rgl package.
DOCX
Experement no 6
PPTX
My favorite slides
PPTX
Introduction to graphics programming in c
TXT
PYTHON PROGRAMS FOR BEGINNERS
PDF
2) quadratics gral form
PPSX
INVERSE FUNCTION
PDF
C Graphics Functions
PPTX
Computer lab (programs)
DOCX
ggtimeseries-->ggplot2 extensions
PDF
Lesson 5: Functions and surfaces
PDF
Computer graphics lab manual
DOCX
R-ggplot2 package Examples
DOCX
Interpolation graph c++
Numpy python cheat_sheet
Kwp2 091217
NumPy Refresher
Basics of Computer graphics lab
Julia Set
Lecture on graphics
Surface3d in R and rgl package.
Experement no 6
My favorite slides
Introduction to graphics programming in c
PYTHON PROGRAMS FOR BEGINNERS
2) quadratics gral form
INVERSE FUNCTION
C Graphics Functions
Computer lab (programs)
ggtimeseries-->ggplot2 extensions
Lesson 5: Functions and surfaces
Computer graphics lab manual
R-ggplot2 package Examples
Interpolation graph c++
Ad

Similar to R scatter plots (20)

PDF
Q plot tutorial
PPTX
MatplotLib.pptx
PPTX
matplotlib.pptxdsfdsfdsfdsdsfdsdfdsfsdf cvvf
PPTX
CIV1900 Matlab - Plotting & Coursework
PPTX
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
PDF
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
PPTX
Chart and graphs in R programming language
PDF
Programming with matlab session 6
PDF
Lectures r-graphics
PPTX
statistical computation using R- an intro..
PPTX
Exploratory data analysis using r
PDF
Python lecture 05
PDF
Data import-cheatsheet
PPTX
Matlab plotting
PDF
Matlab_Pract_lect5details about matlab.pdf
DOCX
Introduction to r
PPTX
R Functions in Dataframe.pptx
PDF
R_CheatSheet.pdf
PPTX
R programming language
PPTX
Lecture_3.pptx
Q plot tutorial
MatplotLib.pptx
matplotlib.pptxdsfdsfdsfdsdsfdsdfdsfsdf cvvf
CIV1900 Matlab - Plotting & Coursework
Seminar PSU 09.04.2013 - 10.04.2013 MiFIT, Arbuzov Vyacheslav
NCCU: Statistics in the Criminal Justice System, R basics and Simulation - Pr...
Chart and graphs in R programming language
Programming with matlab session 6
Lectures r-graphics
statistical computation using R- an intro..
Exploratory data analysis using r
Python lecture 05
Data import-cheatsheet
Matlab plotting
Matlab_Pract_lect5details about matlab.pdf
Introduction to r
R Functions in Dataframe.pptx
R_CheatSheet.pdf
R programming language
Lecture_3.pptx
Ad

More from Abhik Seal (20)

PDF
Chemical data
PPTX
Clinicaldataanalysis in r
PDF
Virtual Screening in Drug Discovery
PDF
Data manipulation on r
PDF
Data handling in r
PPTX
Networks
PDF
Modeling Chemical Datasets
PPTX
Introduction to Adverse Drug Reactions
PPTX
Mapping protein to function
PPTX
Sequencedatabases
PPTX
Chemical File Formats for storing chemical data
PPTX
Understanding Smiles
PDF
Learning chemistry with google
PPTX
3 d virtual screening of pknb inhibitors using data
PPTX
Poster
PDF
Indo us 2012
PDF
Weka guide
PPTX
Pharmacohoreppt
PDF
Document1
PPT
Qsar and drug design ppt
Chemical data
Clinicaldataanalysis in r
Virtual Screening in Drug Discovery
Data manipulation on r
Data handling in r
Networks
Modeling Chemical Datasets
Introduction to Adverse Drug Reactions
Mapping protein to function
Sequencedatabases
Chemical File Formats for storing chemical data
Understanding Smiles
Learning chemistry with google
3 d virtual screening of pknb inhibitors using data
Poster
Indo us 2012
Weka guide
Pharmacohoreppt
Document1
Qsar and drug design ppt

Recently uploaded (20)

PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Cell Types and Its function , kingdom of life
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
01-Introduction-to-Information-Management.pdf
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
VCE English Exam - Section C Student Revision Booklet
PDF
Insiders guide to clinical Medicine.pdf
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Business Ethics Teaching Materials for college
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Cell Types and Its function , kingdom of life
STATICS OF THE RIGID BODIES Hibbelers.pdf
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
01-Introduction-to-Information-Management.pdf
PPH.pptx obstetrics and gynecology in nursing
VCE English Exam - Section C Student Revision Booklet
Insiders guide to clinical Medicine.pdf
human mycosis Human fungal infections are called human mycosis..pptx
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Abdominal Access Techniques with Prof. Dr. R K Mishra
O7-L3 Supply Chain Operations - ICLT Program
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Business Ethics Teaching Materials for college

R scatter plots

  • 1. Abhik Seal: Scatter plots in R I have taken a sample from the Diamonds data from ggplot2 package >sample1<-diamonds[sample(nrow(diamonds),400),] >plot(sample1$price~sample1$carat,#Y~X main = "Relation of diamonds price and carat",# Title xlab ="Price",ylab = "carat",# X and Y label xaxis="i",yaxis="i",# set axis style as internal col ="red",# Color of the dots pch=16)#Set the plotting symbol to filled dots The pch attribute is changed to 2 a different symbol is noticed in figure 2. Fig 1 Fig 2 To set the plot background color to gray we use the bgargument in the par() command >par(bg = “gray”) Then running the plot code you will get something like in fig 3. In par() until the plotting device is closed or a new device is initiated, the background color stays the same. To set the background color for a the plot region a rectangle must be drawn around the plot region figure 4 The script is given below. plot(sample1$price~sample1$carat,type="n") # "n" so that the plotted elements are invisible. x<-par("usr") #gets us the co-ordinates of the plot region in a vector of form c(xleft, xright, ybottom, ytop) rect(x[1],x[3],x[2],x[4],col="gray ") points(plot(sample1$price~sample1$carat,pch=10)
  • 2. Fig 3 Fig 4 If you want to make the title as red, axis values as blue and axis labels as red then you can do this figure 5 plot(sample1$price~sample1$carat,#Y~X main = "Relation of diamonds price and carat",# Title xlab ="Price",ylab = "carat",# X and Y label xaxis="i",yaxis="i",# set axis style as internal col.main ="red",# Color of the dots col.axis="blue", col.lab="red",pch=16) Plotting point, symbols, styles and sizes I used this data (http://www.imdpune.gov.in/ncc_rept/RESEARCH%20REPORT%202.pdf ) from the year 1999 to 2003 and the months from jan to December to plot yearly rainfall. NB: Columns are years and rows are months. Here is the code plot(rain$Year1999 ,main="Yearly Rainfall in India",xlab="Month of the Year",ylab="rainfall",pch=1) points(rain$Year2000,pch=2) points(rain$Year2001,pch=3) points(rain$Year2002,pch=4) points(rain$Year2003,pch=5) legend('top',legend=c("1999","2000","2001","2002","2003"),ncol=5,cex=0.9,bty="n",pch=1:5) Lines format can also be plotted using the lty and lwd arguments in the plot plot(rain$Year1999 ,main="Yearly Rainfall in India",xlab="Month of the Year",ylab="rainfall(mm)",type="l",lty=1,lwd=2,ylim=c(0,400)) lines(rain$Year2000,lty=2,lwd=2) lines(rain$Year2001,lty=3,lwd=2) lines(rain$Year2002,lty=4,lwd=2) lines(rain$Year2003,lty=5,lwd=2) legend('topright',legend=c("1999","2000","2001","2002","2003"),ncol=5,cex=0.9,bty="n",lty=1:5,lwd=2)
  • 3. Lines type code: 0: blank 1: solid (default) 2: dashed 3: dotted 4: dotdash 5: longdash 6: twodash axis(1,at=1:length(rain$Month),labels=rain$Month) lines(rain$Year2000,col="red",type="b",lwd=2) lines(rain$Year2001,col="orange",type="b",lwd=2) lines(rain$Year2002,col="purple",type="b",lwd=2) lines(rain$Year2003,col="yellow",type="b",lwd=2) legend('topright',legend=c("1999","2000","2001","2002","2003"),col= c("black","red","orange","purple","yellow"),ncol=2,cex=0.9,bty="n",lty=1:5,lwd=2) Using xyplot to plot data. I have used the sample1 data from the diamonds dataset . You also require the lattice package for plotting.You can also plot high quality plots using ggplot see my qplot tutorial at slideshare. xyplot(price~carat,data=sample1,groups=color,auto.key=list(corner=c(1,1))) The auto.key use to make a legend at the corner of the plot.
  • 4. Fitting linear model lines using lm() and abline() plot(sample1$price~sample1$carat) lmfit<-lm(sample1$price~sample1$carat) abline(lmfit,col='red') legend("topright", bty="n", legend=paste("R2 is", format(summary(lmfit)$adj.r.squared, digits=4)))# putting the R square in the plot. library(scatterplot3d) scatterplot3d(x=sample1$carat,y=sample1$depth,z=sample1$price,xlab="carat",ylab="depth",zlab="price")#fig scatterplot3d(x=sample1$carat,y=sample1$depth,z=sample1$price,xlab="carat",ylab="depth",zlab="price",pch =16,highlight.3d=TRUE,angle=45,type="h")
  • 5. More on the scatterplot3d at http://www.jstatsoft.org/v08/i11/paper >plot(sample1$price~sample1$carat) >rug(sample1$carat) >rug(sample1$price,side=2,col="blue",ticksize=0.02) The rug function adds a set of lines just above the x and y axis.The closely packed lines represent the density of the data.The side argument takes four values,1: bottom axis (default) ,2: left ,3: top ,4: right.The size of the tick marks are adjusted by ticksize. smoothScatter :smoothScatter() function produces a smoothed color density representation of the scatter plot, obtained through a kernel density estimate. Lab.palette<-colorRampPalette(c("blue","red"), space = "Lab") smoothScatter(sample1$price~sample1$carat,colramp = Lab.palette)