R Visualization with Builtin Functions¶

Feng Li

School of Statistics and Mathematics

Central University of Finance and Economics

feng.li@cufe.edu.cn

https://feng.li/statcomp

>>> Link to Python version 1 2 3

a-picture-is-worth-a-thousand-word

R graphical facilities¶

  • Graphical facilities are an important and extremely versatile component of the R environment.
  • It is possible to use the facilities to display a wide variety of statistical graphs and also to build entirely new types of graph

Plotting commands¶

  • High-level plotting functions create a new plot on the graphics device, possibly with axes, labels, titles and so on.
  • Low-level plotting functions add more information to an existing plot, such as extra points, lines and labels.
  • Interactive graphics functions allow you interactively add information to, or extract information from, an existing plot, using a pointing device such as a mouse.

High-level plotting commands¶

  • Including plot(), hist()...

  • High-level plotting functions are designed to generate a complete plot of the data passed as arguments to the function. Where appropriate, axes, labels and titles are automatically generated (unless you request otherwise.)

  • High-level plotting commands always start a new plot, erasing the current plot if necessary.

Low-level plotting commands¶

  • Sometimes the high-level plotting functions do not produce exactly the kind of plot you desire.

  • In this case, low-level plotting commands can be used to add extra information (such as points, lines or text) to the current plot.

  • Some of the more useful low-level plotting functions are: points(), lines()

Graphics parameters¶

  • When creating graphics, particularly for presentation or publication purposes, R's defaults do not always produce exactly that which is required. You can, however, customize almost every aspect of the display using graphics parameters.

  • The par() function is used to access and modify the list of graphics parameters for the current graphics device.

In [2]:
# Simple high level plot function
n <- 100
a  = rnorm(100)
plot(a, xlab = "Day", ylab = "Return",
     type = "l", col = "red")
In [3]:
# Add points to existing plot
n <- 100
a  = rnorm(n)
plot(a, xlab = "Day", ylab = "Return", type = "l", col = "red")
b  = rnorm(n, sd = 0.3)
points(b, col = "blue", type = "l", lty = "dotted", lwd = 2)
In [4]:
par(mfrow = c(1, 2)) # Using graphical parameter to arrange plots

x <- seq(-5, 5, 1)
plot(x = x, col = "purple", ylab = c(-1, 1), xlab = "hello world!",
     main = "My best plot美图秀秀", type = "p", lwd = 1)
points(x, type = "l")

a  = rnorm(100)
plot(a, xlab = "Day", ylab = "Return", type = "l", col = "red")
b  = rnorm(100, sd = 0.3)
points(b, col = "blue", type = "l", lty = "dotted", lwd = 2)
In [5]:
# the style of axis labels via las=0,1,2,3 
par(las=2)
plot(0,main='change las')
In [6]:
par(mfrow=c(2,4))
par(bty="o")
plot(0,main="par(bty=\"o\")")
par(bty="l")
plot(0,main="par(bty=\"l\")")
par(bty="7")
plot(0,main="par(bty=\"7\")")
par(bty="n")
plot(0,main="par(bty=\"n\")")
par(bty="c")
plot(0,main="par(bty=\"c\")")
par(bty="u")
plot(0,main="par(bty=\"u\")")
par(bty="]") 
plot(0,main="par(bty=\"]\")")
In [7]:
x = seq(-5, 5, 0.1)
fn = dnorm(x)
ft = dt(x, df = 4)
plot(x, fn, xlab = "X", ylab = "Density", main = "Density plot", col = "Blue", type = "l", lwd = 3)
points(x, ft, col = "Red", type = "l", lwd = 3)
In [8]:
x <- rt(100, df=4)                                      # give 100 random t with df 12
hist( x, col = "light blue")                             # make a histgram
In [ ]:

In [9]:
set.seed(1)      # set the seed
par(mar=c(5,5,5,5))  # set the margin
x1<-sort(rnorm(100,mean=20,sd=5)) # asumption this Interest rate
x2<-x1^3 # this is GDP
plot(x2,axes=FALSE,type="l",col="blue",xlab="",ylab="") # plot GDP
axis(1) # add the axis on bottom
axis(2,col="blue") # add the asis on left
par(new=TRUE)  # add new plot on the current graph
plot(x1,,axes=FALSE,type="l",col="red",xlab="",ylab="") # plot Interest rate
axis(4,col="red") # add the axis on right
mtext(c("Time","GDP(mil. $)","Interest rate(%)"),side=c(1,2,4),line=3) # give the three axises labels
title("GDP with interest rate") # give the main title
In [10]:
hist(rnorm(100),xlim=c(-5,5), ylim=c(0,0.7),freq=FALSE)
x<-seq(-5,5,.01)
curve(dnorm(x),add=TRUE)
text(x=0, y=0.6, expression(paste(frac(1,sqrt(2*pi)*sigma),
    exp(-frac(1,2*sigma^2)*((x-mu)^2)))))
# check all symbols in R with `demo(plotmath)`
In [11]:
x<-seq(0,1,.01)
par(lwd=2)
plot(x,dbeta(x,5,1),type="l", ylim=c(0,3), col="green", lty=1,xlab="",ylab="")
lines(x,dbeta(x,.5,.5), col="red",lty=2)
lines(x,dbeta(x,1,3),col="blue",lty=3)
lines(x,dbeta(x,2,2), col="pink",lty=4)
lines(x,dbeta(x,2,5), col="black",lty=5)
lines(x,dbeta(x,1,1),col="orange",lty=6)

legend("top",
c("(5,1)","(.5,.5)","(1,3)","(2,2)","(2,5)","(1,1)"),
lty=c(1,2,3,4,5,6),
col=c("green","red","blue","pink","black","orange"),
ncol=1)
In [12]:
z <- ts(matrix(rt(200 * 8, df = 3), 200, 8), start = c(1961, 1), frequency = 12)
# we can plot some of them for a period (1961.1-1969.12) in multiple frames
z1 <- window(z[,1:3], end = c(1969,12))
plot(z1, type = "b")
# or we can plot them in a single frame
plot(z, plot.type="single", lty=1:3, col=4:2)
In [13]:
set.seed(125) # Polygon
x<-1:200
y<-cumsum(rnorm(200)) # simulate an AR(1) model
int1<-y-1.96 # calculate the 95% level confident interval
int2<-y+1.96
plot(y, type="l", xlab="t",ylab=expression(y[t])) # plot the data
polygon(c(x, rev(x)), c(int1, rev(int2)),col="grey",border=NA) # show the band
lines(y,type="l",col="blue",lwd=2) # plot the line again
In [14]:
x <- seq(-10, 10, .3)
y <- x
rotsinc <- function(x,y)
{
    sinc <- function(x) { y <- sin(x)/x ; y[is.na(y)] <- 1; y }
    sinc( sqrt(x^2+y^2) )
}
z <- outer(x, y, rotsinc)

persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = "lightgreen",
      ltheta = 120, shade = 0.75, ticktype = "detailed",
      xlab = "X", ylab = "Y", zlab = "Z")
title(main = expression(z == sinc(sqrt(x^2 + y^2))))
In [15]:
x<-seq(-10,10,.3)
y<-x
z<-outer(x, y, rotsinc) # the rotsinc is defined in section 2.6
image(x, y, z)
In [16]:
filled.contour(x,y,z) # show the color legend
In [17]:
N <- 50
x <-y<- seq(-1, 1, length=N)
xx <- matrix(x, nrow=N, ncol=N)
yy<-t(xx)
z <- 1 / (1 + xx^2 + (yy + .5 * sin(5*yy))^2)
# here is the contour plot
contour(x, y, z, main = "Contour plot")
In [18]:
image(x, y, z)