Graphics Devices Stat 133 Gaston Sanchez Department of Statistics, - - PowerPoint PPT Presentation

graphics devices
SMART_READER_LITE
LIVE PREVIEW

Graphics Devices Stat 133 Gaston Sanchez Department of Statistics, - - PowerPoint PPT Presentation

Graphics Devices Stat 133 Gaston Sanchez Department of Statistics, UCBerkeley gastonsanchez.com github.com/gastonstat Course web: gastonsanchez.com/teaching/stat133 Graphics Formats How to produce graphical output in different formats 2


slide-1
SLIDE 1

Graphics Devices

Stat 133 Gaston Sanchez

Department of Statistics, UC–Berkeley gastonsanchez.com github.com/gastonstat Course web: gastonsanchez.com/teaching/stat133

slide-2
SLIDE 2

Graphics Formats How to produce graphical output in different formats

2

slide-3
SLIDE 3

Plotting options When creating a plot in R ... Screen display OR Save in File

3

slide-4
SLIDE 4

Plotting options

1 2 3 4 5 6 7 8 9 10 4

slide-5
SLIDE 5

Plotting options

# displaying on screen pie(rep(1, 10), col = rainbow(10)) # saving to a file pdf("dummy_plot.pdf") pie(rep(1, 10), col = rainbow(10)) dev.off()

5

slide-6
SLIDE 6

Plots with R

What happens whe you make a plot in R?

◮ Graphical output is directed to a graphics device ◮ A graphics device must be opened ◮ Subsequent calls to graphics functions directed to a device ◮ Finally, the graphics device is closed 6

slide-7
SLIDE 7

Graphics Devices

2 types of graphics devices

◮ Screen devices ◮ File devices ◮ For more info see ?Devices 7

slide-8
SLIDE 8

Graphics Devices

Default plotting

◮ The default plotting is made via a screen device ◮ e.g. when you call plot(), pie(), or barplot() ◮ The plot appears on a given screen device ◮ If you use RStudio, the plot appears of the RStudio

graphics device

◮ You can specify a particular screen device 8

slide-9
SLIDE 9

Screen Devices

Screen Devices functions Function Graphical Format x11() X Window window (Cairo graphics) windows() Microsoft Windows window quartz() MacOS X Quartz window When displaying on screen, we usually don’t have to worry about graphics devices

9

slide-10
SLIDE 10

Quick examples

If you have a mac try this:

quartz() # open screen device plot(1:10, 1:10, pch = 19) # plot something

After inspecting the plot ...

# close device dev.off()

10

slide-11
SLIDE 11

Quick examples

If you have a PC try this:

windows() # open screen device plot(1:10, 1:10, pch = 19) # plot something

After inspecting the plot ...

# close device dev.off()

11

slide-12
SLIDE 12

Screen Devices in R

◮ dev.new() opens the default device (not in RStudio) ◮ your default device can be found with options("device") ◮ If you use RStudio to plot on screen, the device is

"RStudioGD"

12

slide-13
SLIDE 13

File Devices

File Devices

◮ Instead of displaying a plot on screen, we can save it to a

file

◮ when saving a plot to a file you must use a file device ◮ each file device has its own name ◮ some devices are platform dependent 13

slide-14
SLIDE 14

File Devices

File Devices functions Function Graphical Format postscript() Adobe PostScript file pdf() Portable Document Format svg() SVG file (Linux and MacOS X only) win.metafile() Windows Metafile (Windows only) png() PNG file jpeg() JPEG file bmp() BMP file tiff() TIFF file pictex() LaTeX PicTEX file xfig() xfig FIG file bitmap() Multiple formats via Ghostscript

14

slide-15
SLIDE 15

File Acronyms

File Acronyms Acronym Description PDF Portable Document Format SVG Scalable Vector Graphics PNG Portable Network Graphics JPEG Joint Photographic Experts Group BMP Bitmap TIFF Tagged Image File Format

15

slide-16
SLIDE 16

Output Formats Graphics devices from the output format Vector

  • vs-

Raster

16

slide-17
SLIDE 17

Output Formats

Vector Formats

An image is described by a set of mathematical shapes (e.g. PDF, PostScript, SVG)

Raster Formats

An image consists of an array of pixels, with information such as color recorded for each pixel (e.g. PNG, JPEG, TIFF, all screen devices)

17

slide-18
SLIDE 18

Quick examples

Vector format:

pdf("dummy_plot.pdf") # open device pie(rep(1, 10), col = rainbow(10)) # plot something dev.off() # close device

Raster format:

png("dummy_plot.png") # open device pie(rep(1, 10), col = rainbow(10)) # plot something dev.off() # close device

18

slide-19
SLIDE 19

Vector or Raster?

Vector Formats

Vector formats are superior for images that need to be viewed at a variety of scales (i.e. zoom in and out).

19

slide-20
SLIDE 20

Example: vector image (pdf)

1 2 3 4 5 6 7 8 9 10

20

slide-21
SLIDE 21

Vector or Raster?

Raster Formats

Raster formats tend to be preferred when a plot is visually complex (e.g. many data points), and it will produce smaller files if the image is very complex.

21

slide-22
SLIDE 22

Example: raster image (png)

22

slide-23
SLIDE 23

Vector or Raster?

If further modifications to an R plot will be made using third-party software:

◮ removing a particular form are only possibe with vector

format

◮ modifying pixels of a particular color are only possible with

raster formats Keep in mind: It is easy to convert a vector format to a raster format, while the reverse is almost impossible

23

slide-24
SLIDE 24

Vector Formats

PDF

◮ Good choice of static format ◮ Resizes well, usually portable ◮ Less efficient if a plot has many objects/points ◮ pdf() uses default sans-serif font (Helvetica) ◮ Other standard fonts are supported ◮ For more exotic fonts you should call embedFonts() 24

slide-25
SLIDE 25

Vector Formats

SVG

◮ XML-based format ◮ Good choice for web pages ◮ svg() available in Linux and Mac ◮ SVG output in Windows requires package "Cairo" ◮ Some advanced SVG features are limitted in R 25

slide-26
SLIDE 26

Vector Formats

Windows Metafile

◮ Vector format for Windows ◮ Plots compatible with Microsoft products (e.g. Word,

Excel, PowerPoint)

◮ Can only be produced on Windows systems 26

slide-27
SLIDE 27

Raster (Bitmap) Formats

PNG

◮ Desirable format for simple images (most statistical

graphics)

◮ Good for line drawings or images with solid colors ◮ Good for many, many objects, points= ◮ PNG uses lossless compression: compresses the image

without losing information

◮ PNG does not resize well ◮ Consequently, PNG files can be edited without reducing

quality

◮ Most web browsers can read this format natively 27

slide-28
SLIDE 28

Raster Formats

JPEG

◮ Good for photographs or natural scenes ◮ JPEG uses lossy compression: compresses the image with

some information loss

◮ Consequently, repeatedly editing a JPEG filewill result in

quality reduction

◮ JPEG does not resize well ◮ Better suited for complex images with lots of different

regions (like photographs)

28

slide-29
SLIDE 29

Raster Formats

TIFF

◮ Sophisticated format that allows multiple pages of raster

  • utput within a single file

◮ Supports lossless compression ◮ Less supported by web browsers ◮ Preferred format for publishers of books or journal articles 29

slide-30
SLIDE 30

Raster Formats

Image Size

◮ Size of Raster images is specified in number of pixels

(rahter than physical size in inches)

◮ The physical size of a raster image is determined by the

resolution at which it is viewed

◮ e.g. PNG image 72 pixels wide will be 1 inch wide when

viewed on a screen with a resolution of 72 dpi (dots per inch)

◮ e.g. PNG image 72 pixels wide will be 0.75 inches wide on

a screen with a resolution of 96 dpi

30

slide-31
SLIDE 31

Extension Packages

Extension functions and packages Function Format Package Cairo() Multiple formats "Cairo" tikz() LaTeX PGF, TikZ file "tikzDevice" devSVGTips() SVG file "RSVGTipsDevice" JavaGD Java Swing window "JavaGD"

31

slide-32
SLIDE 32

Data mtcars

head(mtcars, n = 10) ## mpg cyl disp hp drat wt qsec vs am gear carb ## Mazda RX4 21.0 6 160.0 110 3.90 2.620 16.46 1 4 4 ## Mazda RX4 Wag 21.0 6 160.0 110 3.90 2.875 17.02 1 4 4 ## Datsun 710 22.8 4 108.0 93 3.85 2.320 18.61 1 1 4 1 ## Hornet 4 Drive 21.4 6 258.0 110 3.08 3.215 19.44 1 3 1 ## Hornet Sportabout 18.7 8 360.0 175 3.15 3.440 17.02 3 2 ## Valiant 18.1 6 225.0 105 2.76 3.460 20.22 1 3 1 ## Duster 360 14.3 8 360.0 245 3.21 3.570 15.84 3 4 ## Merc 240D 24.4 4 146.7 62 3.69 3.190 20.00 1 4 2 ## Merc 230 22.8 4 140.8 95 3.92 3.150 22.90 1 4 2 ## Merc 280 19.2 6 167.6 123 3.92 3.440 18.30 1 4 4

32

slide-33
SLIDE 33

Different sizes - same resolution

# 600px - 500px png(file = "cars-600-500.png", width = 600, height = 500) plot(mtcars[ ,c('hp', 'mpg')], type = "n", main = "Horsepower and Miles-per-gallon") text(mtcars[ ,c('hp', 'mpg')], lab = rownames(mtcars)) dev.off() # 400px - 350px png(file = "cars-400-350.png", width = 400, height = 350) plot(mtcars[ ,c('hp', 'mpg')], type = "n", main = "Horsepower and Miles-per-gallon") text(mtcars[ ,c('hp', 'mpg')], lab = rownames(mtcars)) dev.off()

33

slide-34
SLIDE 34

cars-600-500.png -vs- cars-400-350.png

Same units = "px", pointsize = 12, res = NA

34

slide-35
SLIDE 35

Same sizes - different resolution

# resolution 72 PPI (pixels-per-inch) png(file = "cars72.png", width = 600, height = 500, res = 72) plot(mtcars[ ,c('hp', 'mpg')], type = "n", main = "Horsepower and Miles-per-gallon") text(mtcars[ ,c('hp', 'mpg')], lab = rownames(mtcars)) dev.off() # resolution 96 PPI (pixels-per-inch) png(file = "cars96.png", width = 600, height = 500, res = 96) plot(mtcars[ ,c('hp', 'mpg')], type = "n", main = "Horsepower and Miles-per-gallon") text(mtcars[ ,c('hp', 'mpg')], lab = rownames(mtcars)) dev.off()

35

slide-36
SLIDE 36

Same sizes, different resolutions

36

slide-37
SLIDE 37

Considerations Plots on Screen

  • vs-

Plots on Print

37

slide-38
SLIDE 38

David Smith’s Recommendations

◮ Use pdf for printing ◮ Use png for web displays ◮ For documents or for detail, go hi-resolution ◮ Choose your dimensions carefully ◮ Think about aspect ratio ◮ Vector formats are good for line drawings and plots with

solid colors

◮ Remove the outer margins, if you’re not using them ◮ Make sure anti-aliasing is enabled ◮ Avoid using JPEG ◮ Be creative http://blog.revolutionanalytics.com/2009/01/ 10-tips-for-making-your-r-graphics-look-their-best.html 38

slide-39
SLIDE 39

PDF

Use pdf for printing

◮ Use pdf if you plan to print your graphic ◮ The graphic is scale-independent ◮ PDF viewers are ubiquitous these days ◮ Easy to create a high-quality printout of a PDF file on

almost any printer

◮ Best choice whenever you want to send the graph as a file

via email, and the recipient needs the best quality possible

39

slide-40
SLIDE 40

PNG

For Web display, use PNG

◮ These days, the best choice is the PNG format ◮ Most browsers can display PNG graphics without trouble ◮ The main choice you need to make when using png() is

the dimensions of the graphic in pixels

◮ Slides 4x3 png plots: width=1024 and height=768 pixels ◮ Slides 16x9 png plots: width=1920 and height=1080

pixels

40

slide-41
SLIDE 41

PNG

Choosing dimensions

◮ For PDF graphs this is easiest to deal with, where you

specify width and height in inches anyway

◮ For raster images is a bit trickier: ◮ R assumes 72 pixels to the inch ◮ When you increase the pixel dimensions you’re also

increasing the implicit size of the graph area

41

slide-42
SLIDE 42

Summary

◮ Plots are created on a graphics device ◮ There are screen devices and file devices ◮ Default graphics on screen are good for exploratory analysis ◮ File devices are useful for presentation-consumption of

graphics

◮ File devices are divided in Vector and Raster formats ◮ Vector formats are good for line drawings and plots with

solid colors

◮ Bitmap formats are good for plots with a large number of

points

42

slide-43
SLIDE 43

More About Graphics

43

slide-44
SLIDE 44

Data starwarstoy.csv

library(readr) git <- 'https://raw.githubusercontent.com/gastonstat/stat133' df <- read_csv(paste0(git, '/master/datasets/starwars.csv')) sw <- na.omit(df[ ,c('name', 'height', 'weight')]) head(sw, n = 5) ## name height weight ## 1 Luke Skywalker 1.72 77 ## 2 Leia Skywalker 1.50 49 ## 3 Obi-Wan Kenobi 1.82 77 ## 4 Han Solo 1.80 80 ## 5 R2-D2 0.96 32

44

slide-45
SLIDE 45

Labeling Points with

◮ text() allows us to add text to a plot ◮ we can use text() to label points

For instance:

with(sw, plot(height, weight)) with(sw, text(height, weight, labels = name))

45

slide-46
SLIDE 46

Labeling Points with

  • 1.0

1.5 2.0 20 40 60 80 100 height weight Luke Skywalker Leia Skywalker Obi−Wan Kenobi Han Solo R2−D2 C−3PO Yoda Chewbacca

46

slide-47
SLIDE 47

Labeling Points with

Use xpd = TRUE to expand the text outside the plotting region:

with(sw, plot(height, weight)) with(sw, text(height, weight, labels = name, xpd = TRUE))

47

slide-48
SLIDE 48

Labeling Points with

  • 1.0

1.5 2.0 20 40 60 80 100 height weight Luke Skywalker Leia Skywalker Obi−Wan Kenobi Han Solo R2−D2 C−3PO Yoda Chewbacca

Some labels are not clearly displayed

48

slide-49
SLIDE 49

Labeling Points

Acronym Description text() Base R spread.labels() "plotrix" thigmophobe.labels() "plotrix" pointLabel() "maptools"

49

slide-50
SLIDE 50

Labeling with spread.labels()

Instead of text() we can use spread.labels():

with(sw, plot(height, weight)) with(sw, spread.labels(height, weight, labels = name))

50

slide-51
SLIDE 51

Labeling with spread.labels()

  • 1.0

1.5 2.0 20 40 60 80 100 height weight Yoda Leia Skywalker C−3PO Luke Skywalker Han Solo Obi−Wan Kenobi Chewbacca

51

slide-52
SLIDE 52

Labeling with thigmophobe.labels()

We can also use thigmophobe.labels():

with(sw, plot(height, weight)) with(sw, thigmophobe.labels(height, weight, labels = name))

52

slide-53
SLIDE 53

Labeling with spread.labels()

  • 1.0

1.5 2.0 20 40 60 80 100 height weight Luke Skywalker Leia Skywalker Obi−Wan Kenobi Han Solo R2−D2 C−3PO Yoda Chewbacca

53

slide-54
SLIDE 54

Labeling with pointLabel()

We can also use pointLabel():

with(sw, plot(height, weight)) with(sw, pointLabel(height, weight, labels = name))

54

slide-55
SLIDE 55

Labeling with pointLabel()

  • 1.0

1.5 2.0 20 40 60 80 100 height weight Luke Skywalker Leia Skywalker Obi−Wan Kenobi Han Solo R2−D2 C−3PO Yoda Chewbacca

55

slide-56
SLIDE 56

Fonts & Formulae

56

slide-57
SLIDE 57

Text and expressions

◮ We can draw text with text() ◮ text() accepts character strings ◮ But it also accepts R expressions resulting from a call to

expression()

◮ An expression is interpreted as a mathematical formula ◮ See ?plotmath for more info 57

slide-58
SLIDE 58

Text and expressions

  • p <- par(mar = c(4, 4, 1, 1))

plot.new() plot.window(xlim = c(0, 1), ylim = c(0, 1)) axis(side = 1) axis(side = 2) text(0.5, 0.8, expression(paste("Temperature (", degree, "C) in 2015"))) text(0.5, 0.6, expression(bar(x) == sum(frac(x[i], n), i==1, n))) text(0.5, 0.4, expression(hat(beta) == (X^t * X)^(-1) * X^t * y)) text(0.5, 0.2, expression(z[i] == sqrt(x[i]^2 + y[i]^2))) par(op)

58

slide-59
SLIDE 59

Text and expressions

0.0 0.2 0.4 0.6 0.8 1.0 0.0 0.2 0.4 0.6 0.8 1.0 Temperature (°C) in 2015 x = ∑

i=1 n xi

n β ^ = (XtX)(−1)Xty zi = xi

2 + yi 2

59

slide-60
SLIDE 60

Text and expressions

◮ We can draw text with text() ◮ text() accepts character strings ◮ But it also accepts R expressions resulting from a call to

expression()

◮ An expressio nis interpreted as a mathematical formula ◮ See ?plotmath for more info 60

slide-61
SLIDE 61

Text and expressions

How to pass a variable to an expression?

year <- 2015

  • p <- par(mar = c(4, 4, 1, 1))

plot.new() plot.window(xlim = c(0, 1), ylim = c(0.4, 0.6)) axis(side = 1) axis(side = 2) text(0.5, 0.5, expression(paste("Temperature (", degree, "C) in ", year))) par(op)

61

slide-62
SLIDE 62

Text and expressions

0.0 0.2 0.4 0.6 0.8 1.0 0.40 0.45 0.50 0.55 0.60 Temperature (°C) in year

62

slide-63
SLIDE 63

Text and expressions

Passing a variable with substitute()

year <- 2015

  • p <- par(mar = c(4, 4, 1, 1))

plot.new() plot.window(xlim = c(0, 1), ylim = c(0.4, 0.6)) axis(side = 1) axis(side = 2) text(0.5, 0.5, substitute( paste("Temperature (", degree, "C) in ", year), list(year = year)) ) par(op)

63

slide-64
SLIDE 64

Text and expressions

0.0 0.2 0.4 0.6 0.8 1.0 0.40 0.45 0.50 0.55 0.60 Temperature (°C) in 2015

64

slide-65
SLIDE 65

R package "googleVis"

65

slide-66
SLIDE 66

Some packages

◮ "googleVis" ◮ "rCharts" ◮ "rMaps" ◮ "rgl" 66

slide-67
SLIDE 67

"googleVis"

install.packages("googleVis") library(googleVis) data(Fruits)

67

slide-68
SLIDE 68

"googleVis"

M <- gvisMotionChart(Fruits, idvar="Fruit", timevar="Year") str(M) print(M) plot(M)

68