6 Plotting and Graphics

6.1 Basics of Plotting

6.1.1 Basic Plot Functions

  • The command plot(x,y) will plot vector x as the independent variable and vector y as the dependent variable.

  • Within the command line, you can specify the title of the graph, the name of the x-axis, and the name of the y-axis.

    • main=’title’

    • xlab=’name of x axis’

    • ylab=’name of y axis’

  • The command lines(x,y) adds a line segment to the plot.

  • The command points(x,y) adds points to the plot.

  • A legend can be created using legend.

demo

demo(graphics)

6.1.2 Simple Plotting Example

Try this yourself:

    x = 1:100
    y = rnorm(100,3,1) # 100 random normal deviates with mean=3, sd=1
    plot(x,y)

    plot(x,y,main='My First Plot')

    # change point type
    plot(x,y,pch=3)

    # change color
    plot(x,y,pch=4,col=2)
    # draw lines between points
    lines(x,y,col=3)

6.1.3 More Plotting

z=sort(y)
# plot a sorted variable vs x
plot(x,z,main='Random Normal Numbers',
xlab='Index',ylab='Random Number')


# another example
plot(-4:4,-4:4) 
# and add a point at (0,2) to the plot
points(0,2,pch=6,col=12)

6.1.4 More Plotting

# check margin and outer margin settings
par(c("mar", "oma")) 
plot(x,y)
par(oma=c(1,1,1,1))  # set outer margin
plot(x,y)
par(mar=c(2.5,2.1,2.1,1)) # set margin
plot(x,y)


# A basic histogram
hist(z, main="Histogram",
    sub="Random normal")


# A "density" plot
plot(density(z), main="Density plot",
    sub="Random normal")


# A smaller "bandwidth" to capture more detail
plot(density(z, adjust=0.5),
  sub="smaller bandwidth")

6.1.5 Graphics Devices and Saving Plots

  • to make a plot directly to a file use: png(), postscript(), etc.

  • R can have multiple graphics “devices” open.

    • To see a list of active devices: dev.list()

    • To close the most recent device: dev.off()

    • To close device 5: dev.off(5)

    • To use device 5: dev.set(5)

6.1.6 More Plotting

  • Save a png image to a file

    png(file="myplot.png",width=480,height=480)
    plot(density(z,adjust=2.0),sub="larger bandwidth")
    dev.off()
  • On your own, save a pdf to a file. NOTE: The dimensions in pdf() are in inches

  • Multiple plots on the same page:

    par(mfrow=c(2,1))
    plot(density(z,adjust=2.0),sub="larger bandwidth")
    hist(z)
    
    
    # use dev.off() to turn off the two-row plotting