etienne — Jun 6, 2013, 10:42 PM
# base graphics tutorial
# Etienne Laliberte
# June 4, 2013
# let's get started: a simple example
data(pressure)
plot(pressure)
# 3 alternative ways of specifying x and y
# note that labels change
plot(pressure[,1], pressure[,2])
plot(pressure$temperature, pressure$pressure)
plot(pressure ~ temperature, data = pressure)
# plot is a generic function
hc <- hclust(dist(USArrests) )
plot(hc)
######## graphics devices
windows() # opens a new windows device
plot(pressure) # draws a scatterplot in active device
dev.off() # closes active device; you can also use red 'X' in window
pdf
2
pdf("pressure.pdf") # opens a pdf device; check in your working directory
# a pdf file has been created but you cannot open it yet...
plot(pressure) # draws the same scatterplot in active pdf device
dev.off() # closes the pdf device; you can now open the file
pdf
2
png("pressure.png") # opens a png device
plot(pressure) # draws the same scatterplot in active pdf device
dev.off() # closes the png device; you can now open the file
pdf
2
# now let's make it a bit more confusing
# try following along!
windows() # opens a windows device
pdf("pressure2.pdf") # opens a pdf device
png("pressure2.png") # opens a png device
dev.list() # lists of all active devices
pdf windows pdf png
2 3 4 5
dev.cur() # tells you which device is the active one
png
5
dev.set(dev.prev()) # sets active device to previous one
pdf
4
hist(pressure[,2]) # draws histogram in active device
### question: where is the plot?
dev.set(dev.next()) # sets active device as the next one
png
5
hist(pressure[,2]) # draws a histogram in active device
### question: where is the scatterplot?
dev.set(which = 2) # sets second device as the active one
pdf
2
hist(pressure[,2]) # draws a histogram in current device
### plot should be in windows device!
dev.off() # closes the current device
windows
3
graphics.off() # closes all graphics devices
### now you should be able to open both pressure2.pdf and pressure2.png
# multiple pages of output
pdf("manypages.pdf",
onefile = TRUE,
width = 3,
height = 3)
plot(pressure, type = "p")
plot(pressure, type = "l")
plot(pressure, type = "b")
plot(pressure, type = "h")
dev.off()
null device
1
# multiple files
png("pressure%03d.png",
width = 3,
height = 3,
res = 300, units = "in")
plot(pressure, type = "p")
plot(pressure, type = "l")
plot(pressure, type = "b")
plot(pressure, type = "h")
dev.off()
null device
1
#### if you have extra time during the course,
### you can go through the basegraphics_EXTRAS.R script