Web EndMemo

R Scatter Plots Example

( Scatter Plot Online )



Following is a csv file example, we will draw a Scatter Plot of the "Expression" and "Quality" values:


Let first read in the data from the file:

    > x <- read.csv("scatterplot.csv",header=T,sep="\t")
    > x <- t(x)
    > ex <- as.numeric(x[2,1:ncol(x)])
    > qu <- as.numeric(x[3,1:ncol(x)])

Draw a Scatter Plot:

    > plot(ex,qu)


If we want to draw different subtype in different color and symbol, we need more work like follows:

    > plot(ex,qu,col="white",xlab="Expression", ylab="Quality")
    > points(ex[1:143],qu[1:143],col="red",pch=3,cex=.6) #Subtype A
    > points(ex[144:218],qu[144:218],col="blue",pch=19,cex=.6) #Subtype B
    > points(ex[219:ncol(x)],qu[219:ncol(x)],col="black",,pch=1,cex=.6) #Subtype C
    > abline(lm(ex[144:218] ~ qu[144:218]),col="blue") #regression expression ~ quality of B


Following code can add a legend on the right:

    > layout(matrix(c(1,2), nrow = 1), widths = c(0.7, 0.3))
    > par(mar = c(5, 4, 4, 2) + 0.1)
    > plot(ex,qu,col="white",xlab="Expression", ylab="Quality")
    > points(ex[219:ncol(x)],qu[219:ncol(x)],col="black",,pch=1,cex=.6)
    > points(ex[144:218],qu[144:218],col="blue",pch=19,cex=.6)
    > points(ex[1:143],qu[1:143],col="red",cex=.6,pch=3)
    > abline(lm(ex[144:218] ~ qu[144:218]),col="blue")
    > par(mar = c(5, 0, 4, 1) + 0.1)
    > plot(ex,qu,axes=FALSE,ann=FALSE, col="white")
    > legend(x=-2.5,y=1.2,c("A (n=146)","B (n=77)","C (n=85)"),cex=.8, pch=c(1,19,3),col=c("black","blue", "red"))


R package "scatterplot3d" can be used to draw 3D scatter plots, to install this package:

    > install.packages("scatterplot3d",repos="http://R-Forge.R-project.org")

To draw a 3D scatter plot based on the "Expression", "Quality" and "Height" values:

    > library(scatterplot3d)
    > hi <- as.numeric(x[4,1:ncol(x)])
    > scatterplot3d(ex,qu,hi,pch=20,highlight.3d=T)


We can add more parameters like:

    > scatterplot3d(ex,qu,hi,pch=20,highlight.3d=T,type="h")




Download the csv file and the R source code:

Data File
R Source Code File