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

  1. In RStudio IDE:

Plots panel -> Export -> Save as Image or Save as PDF

#preference:http://www.sthda.com/english/wiki/r-base-graphs
  1. Using R codes:
    1. Choose the format
    1. Create the graphs
    1. 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 file

  • png("rplot.png") : png file

  • jpeg("rplot.jpg") : jpeg file

  • postscript("rplot.ps"): postscript file

  • bmp("rplot.bmp") : bmp file

  • win.metafile("rplot.wmf") : windows metafile