R Graphics - Department of Statisticspaul/Talks/Rgraphics.pdf · R Graphics – p.36/47. Graphical...

Post on 23-Mar-2018

217 views 0 download

Transcript of R Graphics - Department of Statisticspaul/Talks/Rgraphics.pdf · R Graphics – p.36/47. Graphical...

R GraphicsPaul Murrell

paul@stat.auckland.ac.nz

The University of Auckland

R Graphics – p.1/47

Overview

Standard (base) R graphics

grid graphics

Graphics Regions and Coordinate SystemsDirecting Graphics OutputProducing Graphics OutputPlots from First Principles

grid and lattice

R Graphics – p.2/47

R Graphics Fundamentals

Graphics Regions and Coordinate SystemsOuter MarginsFigure RegionsFigure MarginsPlot Regions

Directing Graphics OutputWhich graphics functions to use

Producing Graphics OutputGraphical parameters

R Graphics – p.3/47

Outer Margins and Figure Region

Figure Region

Outer margin 1

Out

er m

argi

n 2

Outer margin 3

Out

er m

argi

n 4

par(oma=c(0, 0, 0, 0), omi=)par(mfrow=c(1, 1), mfcol=c(1, 1), fig=, fin=)

R Graphics – p.4/47

Arbitrary Figure Regions

Figure 1

Figure 2

par(fig=c(0.1, 0.6, 0.1, 0.6))par(new=T)par(fig=c(0.4, 0.9, 0.4, 0.8))

R Graphics – p.5/47

Figure Margins and Plot Region

Plot Region

Figure Margin 1

Fig

ure

Mar

gin

2

Figure Margin 3

Fig

ure

Mar

gin

4

Outer margin 1

Out

er m

argi

n 2

Outer margin 3

Out

er m

argi

n 4

par(mar=c(5.1, 4.1, 4.1, 2.1), mai=)par(pty="m", pin=, plt=)

R Graphics – p.6/47

User Coordinates

Minimum x value Maximum x value

Min

imum

y v

alue

Max

imum

y v

alue

The location (xi, yi)

xi

y i

<plot.function>(..., xlim=, ylim=)par(xaxs="r", yaxs="r")

R Graphics – p.7/47

Figure Margin Coordinates

FigureMargin

1

0 11

0 lines

3 lines

FigureMargin

2

0

11

0 lines3 lines

R Graphics – p.8/47

Outer Margin Coordinates

0

11

Cur

rent

Plo

t

Outer Margin 1

0 11

0 lin

es

3 lin

es

0 110

11

Cur

rent

Plo

t

Outer Margin 1

0 1

0 lin

es

3 lin

es

R Graphics – p.9/47

Directing Graphics Output

Plot Region Figure Margins Outer Marginstext() mtext() mtext()

points() axis()

lines()

arrows()

polygon()

segments()

box()

abline()

R Graphics – p.10/47

Graphical Parameters

Permanent settingspar(<param>=)

Temporary settings<plot.function>(..., <param>=)

col colour of lines, text, ...lwd line widthlty line typefont font face (plain, bold, italic)pch type of plotting symbolsrt string rotation

R Graphics – p.11/47

Plots from First Principles

0 2 4 6 8 10

02

46

810

1:10

R Graphics – p.12/47

Plots from First Principles

Create regions and coordinate systems> par(omi=rep(0, 4), mar=c(5.1, 4.1, 4.1, 2.1),

mfrow=c(1, 1))> plot(0, type="n", xlim=c(0, 10), ylim=c(0,10),+ axes=F, xlab="", ylab="")

Draw data symbols in plot region> par(col=1, lty=1, lwd=1, cex=1, srt=0)> points(1:10)

Draw axes and labels in the figure margins> box()> axis(1)> axis(2)> mtext("1:10", side=2, line=3)

R Graphics – p.13/47

Plots from First Principles

02

46

810

1214

Group 1

Group 2

Group 3

Group 4

R Graphics – p.14/47

Plots from First Principles

Create area for barplot, leaving room for legend.par(fig=c(0, 0.8, 0, 1), mar=c(4, 4, 4, 2))

Draw barplot.barplot(matrix(sample(1:4, 16, replace=T),

ncol=4),angle=45, density=1:4*10, col=1)

Stay on same page and set up region and coordinates forlegend.par(new=T)par(fig=c(0.8, 1, 0, 1), mar=c(4, 0, 4, 2))plot(0, xlim=c(0, 1), ylim=c(0, 5), axes=F,

xlab="", ylab="", type="n")

R Graphics – p.15/47

Plots from First Principles

Figure out what 0.5” is in user coordinates.size <- par("cxy")/par("cin")*.5

Draw legend elements and a dashed border. .box(lty=2)for (i in 1:4)polygon(c(0.5 - size[1]/2, 0.5 - size[1]/2,

0.5 + size[1]/2, 0.5 + size[1]/2),c(i, i + size[2], i + size[2], i),angle=45, density=i*10)

text(0.5, i-0.2, paste("Group", i))

R Graphics – p.16/47

grid Graphics Fundamentals

Graphics Regions and Coordinate SystemsViewportsLayouts

Directing Graphics OutputUnits

Producing Graphics OutputGraphical primitives and componentsGraphical parameters

R Graphics – p.17/47

Viewports

0

1

0

1

0.5n

pc

0.25

npc

0.5npc

0.5npc

viewport(x = 0.5, y = 0.5, width = 0.5,height = 0.25, angle=45)

R Graphics – p.18/47

Pushing and Popping Viewports

vp1 <- viewport(x=0, y=0.5, w=0.5, h=0.5,just=c("left", "bottom"))

vp2 <- viewport(x=0.5, y=0, w=0.5, h=0.5,just=c("left", "bottom"))

push.viewport(vp1)grid.text("Some drawing in graphics region 1",

y=0.8)pop.viewport()push.viewport(vp2)grid.text("Some drawing in graphics region 2",

y=0.8)pop.viewport()push.viewport(vp1)grid.text("MORE drawing in graphics region 1",

y=0.2)pop.viewport()

R Graphics – p.19/47

Pushing and Popping Viewports

Some drawing in graphics region 1

Some drawing in graphics region 2

MORE drawing in graphics region 1

R Graphics – p.20/47

The Viewport Stack

vp <- viewport(width = 0.5, height = 0.5)push.viewport(vp)grid.rect(gp=gpar(col="grey"))grid.text("quarter of the page",

y=0.85)push.viewport(vp)grid.rect()grid.text("quarter of the\nprevious viewport")pop.viewport(2)

R Graphics – p.21/47

The Viewport Stack

quarter of the page

quarter of theprevious viewport

R Graphics – p.22/47

Directing Graphics Output

push.viewport(viewport(y=unit(3, "lines"),

width=0.9,height=0.8, just="bottom",xscale=c(0, 100)))

grid.rect(gp=gpar(col="grey"))grid.xaxis()push.viewport(viewport(x=unit(60, "native"),

y=unit(0.5, "npc"),width=unit(1, "strwidth",

"coordinates for everyone"),height=unit(3, "inches")))

grid.rect()grid.text("coordinates for everyone")pop.viewport(2)

R Graphics – p.23/47

Directing Graphics Output

0 20 40 60 80 100

coordinates for everyone

R Graphics – p.24/47

Units

"npc" Normalised Parent Coordinates. Treatsthe bottom-left corner of the current view-port as the location

� ���

� �

and the top-rightcorner as

���

� �

."native" Locations and sizes are relative to the x-

and y-scales for the current viewport."inches" Locations and sizes are in terms of phys-

ical inches. For locations,

� ���

� �

is at thebottom-left of the viewport.

"cm" Same as "inches", except in centime-tres.

R Graphics – p.25/47

Units

"char" Locations and sizes are specified interms of multiples of the current nominalfontheight.

"lines" Locations and sizes are specified interms of multiples of the height ofa line of text (dependent on boththe current fontsize and the currentlineheight).

"snpc" Square Normalised Parent Coordinates.Locations and size are expressed as aproportion of the smaller of the width andheight of the current viewport.

R Graphics – p.26/47

Units

"strwidth" Locations and sizes are expressed asmultiples of the width of a given string(dependent on the string and the currentfontsize).

"strheight" Like "strwidth"."grobwidth" Locations and sizes are expressed as

multiples of the width of a given graphicalobject (dependent on the current state ofthe graphical object).

"grobheight" Like "grobwidth".

R Graphics – p.27/47

Working with Units

> unit(1, "npc")[1] 1npc

> unit(1:3/4, "npc")[1] 0.25npc 0.5npc 0.75npc

> unit(1:3/4, "npc")[2][1] 0.5npc

R Graphics – p.28/47

Working with Units

> unit(1:3/4, "npc") + unit(1, "inches")[1] 0.25npc+1inches 0.5npc+1inches 0.75npc+1inches

> min(unit(0.5, "npc"), unit(1, "inches"))x[1] min(0.5npc, 1inches)

> unit.c(unit(0.5, "npc"),+ unit(2, "inches") + unit(1:3/4, "npc"),+ unit(1, "strwidth", "hi there"))[1] 0.5npc 2inches+0.25npc[3] 2inches+0.5npc 2inches+0.75npc[5] 1strwidth

R Graphics – p.29/47

Layouts

push.viewport(viewport(layout=grid.layout(4, 5)))grid.rect(gp=gpar(col="grey"))grid.segments(c(1:4/5, rep(0, 3)),

c(rep(0, 4), 1:3/4),c(1:4/5, rep(1, 3)),c(rep(1, 4), 1:3/4),

gp=gpar(col="grey"))push.viewport(viewport(layout.pos.col=2:3,

layout.pos.row=3))grid.rect(gp=gpar(lwd=3))pop.viewport(2)

R Graphics – p.30/47

Layouts

R Graphics – p.31/47

Layouts

grid.layout(4, 4,widths=unit(c(3, 1, 1, 1),

c("lines", "null", "null", "cm")),heights=unit(c(1, 1, 2, 3),

c("cm", "null", "null", "lines")))

R Graphics – p.32/47

Layouts

(1, 1)1cm

3lines

(1, 2)

1null

(1, 3)

1null

(1, 4) 1cm

1cm

(2, 1)1null (2, 2) (2, 3) (2, 4) 1null

(3, 1)2null (3, 2) (3, 3) (3, 4) 2null

(4, 1)3lines

3lines

(4, 2)

1null

(4, 3)

1null

(4, 4)

1cm

3lines

R Graphics – p.33/47

Producing Graphics Output

grid.text Can specify angle of rotation.grid.rect

grid.circle

grid.polygon

grid.points Can specify type of plotting symbol.grid.lines

grid.segments

grid.grill Convenience function for drawing grid linesgrid.move.to

grid.line.to

grid.xaxis Top or bottom axisgrid.yaxis Left or right axis

R Graphics – p.34/47

Graphical Parameters

Specify using gp argument of viewport or graphical object.

Viewport settings are “inherited” by subsequent viewports andgraphical objects.

col colour of lines, text, ...fill colour for filling polygons, ...lwd line widthlty line typefontface font face (plain, bold, italic)fontfamily font family (Helvetica, Hershey, ...)fontsize font size (points)

R Graphics – p.35/47

Graphical Parameters

push.viewport(viewport(gp=gpar(fill="grey",

fontface="italic")))grid.rect()grid.rect(width=0.8, height=0.6,

gp=gpar(fill="white"))grid.text("This text and the inner rectangle\n

have specified their own gpar settings",y=0.75, gp=gpar(fontface="plain"))

grid.text("This text and the outer rectangle\naccept the gpar settings of the viewport",y=0.25)

pop.viewport()

R Graphics – p.36/47

Graphical Parameters

This text and the inner rectanglehave specified their own gpar settings

This text and the outer rectangleaccept the gpar settings of the viewport

R Graphics – p.37/47

Plots from First Principles

x <- y <- 1:10push.viewport(plotViewport(c(5.1, 4.1, 4.1, 2.1)))push.viewport(dataViewport(x, y))grid.rect()grid.xaxis()grid.yaxis()grid.points(x, y)grid.text("1:10", x=unit(-3, "lines"), rot=90)pop.viewport(2)

R Graphics – p.38/47

Plots from First Principles

2 4 6 8 10

2

4

6

8

10

1:10

R Graphics – p.39/47

Barplot with Legend

bp <- function(barData)

nbars <- dim(barData)[2]

nmeasures <- dim(barData)[1]

barTotals <- rbind(rep(0, nbars), apply(barData, 2, cumsum))

barYscale <- c(0, max(barTotals)*1.05)

push.viewport(plotViewport(c(5, 4, 4, 1),

yscale=barYscale,

layout=grid.layout(1, nbars)))

grid.rect()

grid.yaxis()

for (i in 1:nbars)

push.viewport(viewport(layout.pos.col=i, yscale=barYscale))

grid.rect(x=rep(0.5, nmeasures),

y=unit(barTotals[1:nmeasures, i], "native"),

height=unit(diff(barTotals[,i]), "native"),

width=0.8, just="bottom", gp=gpar(fill=boxColours))

pop.viewport()

pop.viewport()

R Graphics – p.40/47

Barplot with Legend

leg <- function(legLabels)

nlabels <- length(legLabels)push.viewport(viewport(layout=grid.layout(4, 1)))for (i in 1:nlabels)

push.viewport(viewport(layout.pos.row=i))grid.rect(width=boxSize, height=boxSize,

just="bottom",gp=gpar(fill=boxColours[i]))

grid.text(legLabels[i],y=unit(0.5, "npc") - unit(1, "lines"))

pop.viewport()

pop.viewport()

R Graphics – p.41/47

Barplot with Legend

barData <- matrix(sample(1:4, 16, replace=T), ncol=4)

boxColours <- 1:4

legLabels <- c("Group A", "Group B", "Group C", "Something Longer")

boxSize <- unit(0.5, "inches")

legend.width <- max(unit(rep(1, length(legLabels)),

"strwidth", as.list(legLabels)) +

unit(2, "lines"),

unit(0.5, "inches") + unit(2, "lines"))

push.viewport(viewport(layout=grid.layout(1, 2,

widths=unit.c(unit(1,"null"), legend.width))))

push.viewport(viewport(layout.pos.col=1))

bp(barData)

pop.viewport()

push.viewport(viewport(layout.pos.col=2))

push.viewport(plotViewport(c(5, 0, 4, 0)))

leg(legLabels)

pop.viewport(3)

R Graphics – p.42/47

Barplot with Legend

0

2

4

6

8

10Group A

Group B

Group C

Something Longer

R Graphics – p.43/47

Adding grid to lattice

x <- rnorm(100)y <- rnorm(100)g <- sample(1:8, 100, replace=T)

print.trellis(xyplot(y ˜ x | g,

panel=function(x, y)�panel.xyplot(x, y);grid.lines(unit(c(0, 1), "npc"),

unit(0, "native"),gp=gpar(col="grey"))

))

R Graphics – p.44/47

Adding grid to lattice

x

y

−2

−1

0

1

2

−2 −1 0 1 2

g g

−2 −1 0 1 2

g

g g

−2

−1

0

1

2

g

−2

−1

0

1

2

g g

−2 −1 0 1 2

R Graphics – p.45/47

Adding lattice to grid

someText <- "A panel of text\nproduced using\n

raw grid code\nthat describes\n

the plot\nto the right."

latticePlot <- xyplot(y ˜ x | g, layout=c(2, 4))

grid.rect(gp=gpar(lty="dashed"))

push.viewport(viewport(layout=grid.layout(1, 2,

widths=unit.c(unit(1, "strwidth", someText) + unit(2, "cm"),

unit(1, "null")))))

push.viewport(viewport(layout.pos.col=1))

grid.rect(gp=gpar(fill="light grey"))

grid.text(someText, x=unit(1, "cm"),

y=unit(1, "npc") - unit(1, "inches"),

just=c("left", "top"))

pop.viewport()

push.viewport(viewport(layout.pos.col=2))

print.trellis(latticePlot, newpage=FALSE)

pop.viewport(2)

R Graphics – p.46/47

Adding lattice to grid

A panel of textproduced usingraw grid codethat describesthe plotto the right.

x

y

−2−1

0123

−2 0 2

g g

g

−2−10123

g

−2−1

0123

g g

g

−2−10123

g

−2 0 2

R Graphics – p.47/47