Chapter 2 Creating and Saving Graphs in R
Creating graphs:
Used mtcars
(Motor Trend Car Road Tests from default dataset) dataset for this section:
?mtcars
## starting httpd help server ... done
head(mtcars,5)
## mpg cyl disp hp drat wt qsec vs am gear carb
## Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
## Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
## Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
## Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
## Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
Created a graphs with plot()
function:
plot(x = mtcars$wt, y = mtcars$mpg,
pch = 16, frame = FALSE,
xlab = "Weight (1000 lbs)", ylab = "Miles/(US) gallon", col = "#2E9FDF")
Saving graphs:
There are two ways of saving graphs in R
- In RStudio IDE:
Plots panel -> Export -> Save as Image or Save as PDF
#preference:http://www.sthda.com/english/wiki/r-base-graphs
- Using R codes:
- Choose the format
- Create the graphs
- Enter the dev.off() command
Example->
Note: The file you save are in the current working directory.
The command to get directory is getwd()
# 1. Choose the format
png("rplot.jpg") #width = 25, height = "25"
# 2. Create the graphs
plot(x = mtcars$wt, y = mtcars$mpg,
pch = 16, frame = FALSE,
xlab = "wt", ylab = "mpg", col = "#2E9FDF")
# 3. Save the file with dev.off() command in directory
dev.off()
## png
## 2
File formats for exporting plots are:
pdf("rplot.pdf")
: pdf filepng("rplot.png")
: png filejpeg("rplot.jpg")
: jpeg filepostscript("rplot.ps")
: postscript filebmp("rplot.bmp")
: bmp filewin.metafile("rplot.wmf")
: windows metafile