Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
R in Action, Second Edition.pdf
Скачиваний:
540
Добавлен:
26.03.2016
Размер:
20.33 Mб
Скачать

Modifying the appearance of ggplot2 graphs

455

The curve for males appears to increase from 0 to about 30 years and then decrease. The curve for women rises from 0 to 40 years. No women in the dataset received their degree more than 40 years ago. For most of the range where both genders have data, men have received higher salaries.

Stat functions

In this section, you’ve added smoothed lines to scatter plots. The ggplot2 package contains a wide range of statistical functions (called stat functions) for calculating the quantities necessary to produce a variety of data visualizations. Typically, geom functions call the stat functions implicitly, and you won’t need to deal with them directly. But it’s useful to know they exist. Each stat function has help pages that can aid you in understanding how the geoms work.

For example, the geom_smooth() function relies on the stat_smooth() function to calculate the quantities needed to plot a fitted line and its confidence limits. The help page for geom_smooth() is sparse, but the help page for stat_smooth() contains a wealth of useful information. When exploring how a geom works and what options are available, be sure to check out both the geom function and its related stat function(s).

19.7 Modifying the appearance of ggplot2 graphs

In chapter 3, you saw how to customize base graphics using graphical parameters placed in the par() function or specific plotting functions. Unfortunately, changing base graphics parameters has no effect on ggplot2 graphs. Instead, the ggplot2 package offers specific functions for changing the appearance of its graphs.

In this section, we’ll look at several functions that allow you to customize the appearance of ggplot2 graphs. You’ll learn how to customize the appearance of axes (limits, tick marks, and tick mark labels), the placement and content of legends, and the colors used to represent variable values. You’ll also learn how to create custom themes (allowing you to add a consistent look and feel to your graphs) and arrange several plots into a single graph.

19.7.1Axes

The ggplot2 package automatically creates plot axes with tick marks, tick mark labels, and axis labels. Often they look fine, but occasionally you’ll want to take greater control over their appearance. You’ve already seen how to use the labs() function to add a title and change the axis labels. In this section, you’ll customize the axes themselves. Table 19.6 contains functions that are useful for customizing axes.

Table 19.6 Functions that control the appearance of axes and tick marks

Function

Options

 

 

scale_x_continuous(), breaks= specifies tick marks, labels= specifies labels for tick marks, scale_y_continuous() and limits= controls the range of the values displayed.

456

CHAPTER 19 Advanced graphics with ggplot2

Table 19.6 Functions that control the appearance of axes and tick marks (continued)

Function

Options

 

 

scale_x_discrete(), breaks= places and orders the levels of a factor, labels= specifies scale_y_discrete() the labels for these levels, and limits= indicates which levels should

be displayed.

coord_flip()

Reverses the x and y axes.

As you can see, ggplot2 functions distinguish between the x- and y-axes and whether an axis represents a continuous or discrete (factor) variable.

Let’s apply these functions to a graph with grouped box plots for faculty salaries by rank and sex. The code is as follows:

data(Salaries,package="car")

library(ggplot2)

ggplot(data=Salaries, aes(x=rank, y=salary, fill=sex)) + geom_boxplot() +

scale_x_discrete(breaks=c("AsstProf", "AssocProf", "Prof"), labels=c("Assistant\nProfessor",

"Associate\nProfessor", "Full\nProfessor")) +

scale_y_continuous(breaks=c(50000, 100000, 150000, 200000), labels=c("$50K", "$100K", "$150K", "$200K")) +

labs(title="Faculty Salary by Rank and Sex", x="", y="")

The resulting graph is provided in figure 19.16.

Clearly, average income goes up with rank, and men make more than women within each teaching rank. (For a more complete picture, try controlling for years since Ph.D.)

Faculty Salary by Rank and Sex

$200K

$150K

$100K

$50K

Assistant

Associate

Full

Professor

Professor

Professor

sex

Female

Male

Figure 19.16 Box plots of faculty salaries grouped by academic rank and sex. The axis text has been customized.

Modifying the appearance of ggplot2 graphs

457

19.7.2Legends

Legends are guides that indicate how visual characteristics like color, shape, and size represent qualities of the data. The ggplot2 package generates legends automatically, and in many cases they suffice quite well. At other times, you may want to customize them. The title and placement are the most commonly customized characteristics.

When modifying a legend’s title, you have to take into account whether the legend is based on color, fill, size, shape, or a combination. In figure 19.16, the legend represents the fill aesthetic (as you can see in the aes() function), so you can change the title by adding fill="mytitle" to the labs() function.

The placement of the legend is controlled by the legend.position option in the theme() function. Possible values include "left", "top", "right" (the default), and "bottom". Alternatively, you can specify a two-element vector that gives the position within the graph. Let’s modify the graph in figure 19.16 so that the legend appears in the upper-left corner and the title is changed from sex to Gender. This can be accomplished with the following code:

data(Salaries,package="car")

library(ggplot2)

ggplot(data=Salaries, aes(x=rank, y=salary, fill=sex)) + geom_boxplot() +

scale_x_discrete(breaks=c("AsstProf", "AssocProf", "Prof"), labels=c("Assistant\nProfessor",

"Associate\nProfessor", "Full\nProfessor")) +

scale_y_continuous(breaks=c(50000, 100000, 150000, 200000), labels=c("$50K", "$100K", "$150K", "$200K")) +

labs(title="Faculty Salary by Rank and Gender", x="", y="", fill="Gender") +

theme(legend.position=c(.1,.8))

The results are shown in figure 19.17.

Figure 19.17 Box plots of faculty salaries grouped by academic rank. The axis text has been customized, along with the legend title and position.

Faculty Salary by Rank and Gender

Gender

$200K Female

Male

$150K

$100K

$50K

Assistant

Associate

Full

Professor

Professor

Professor

458

CHAPTER 19 Advanced graphics with ggplot2

In this example, the upper-left corner of the legend was placed 10% from the left edge and 80% from the bottom edge of the graph. If you want to omit the legend, use legend.position="none". The theme() function can change many aspects of a ggplot2 graph’s appearance; other examples are given in section 19.7.4.

19.7.3Scales

The ggplot2 package uses scales to map observations from the data space to the visual space. Scales apply to both continuous and discrete variables. In figure 19.15, a continuous scale was used to map the numeric values of the yrs.since.phd variable to distances along the x-axis and map the numeric values of the salary variable to distances along the y-axis.

Continuous scales can map numeric variables to other characteristics of the plot. Consider the following code:

ggplot(mtcars, aes(x=wt, y=mpg, size=disp)) + geom_point(shape=21, color="black", fill="cornsilk") +

labs(x="Weight", y="Miles Per Gallon",

title="Bubble Chart", size="Engine\nDisplacement")

The aes() parameter size=disp generates a scale for the continuous variable disp (engine displacement) and uses it to control the size of the points. The result is the bubble chart presented in figure 19.18. The graph shows that auto mileage decreases with both weight and engine displacement.

Miles Per Gallon

Bubble Chart

35

30

25

20

15

10

2

3

4

5

Engine

Displacement

100

200

300

400

Figure 19.18 Bubble chart of auto weight by mileage, with point size representing engine displacement

Weight

Modifying the appearance of ggplot2 graphs

459

salary

200000

150000

100000

50000

0

20

40

yrs.since.phd

rank

AsstProf

AssocProf

Prof

Figure 19.19 Scatterplot of salary vs. experience for assistant, associate, and full professors. Point colors have been specified manually.

In the discrete case, you can use a scale to associate visual cues (for example, color, shape, line type, size, and transparency) with the levels of a factor. The code

data(Salaries, package="car")

ggplot(data=Salaries, aes(x=yrs.since.phd, y=salary, color=rank)) + scale_color_manual(values=c("orange", "olivedrab", "navy")) + geom_point(size=2)

uses the scale_color_manual() function to set the point colors for the three academic ranks. The results are displayed in figure 19.19.

If you’re color challenged like I am (does purple go with orange?), you can use color presets via the scale_color_brewer() and scale_fill_brewer() functions to specify attractive color sets. For example, try the code

ggplot(data=Salaries, aes(x=yrs.since.phd, y=salary, color=rank)) + scale_color_brewer(palette="Set1") + geom_point(size=2)

and see what you get. Replacing palette="Set1" with another value (such as "Set2",

"Set3", "Pastel1", "Pastel2", "Paired", "Dark2", or "Accent") will result in a different color scheme. To see the available color sets, use

library(RColorBrewer)

display.brewer.all()

to generate a display. For more information, see help(scale_color_brewer) and the ColorBrewer homepage (http://colorbrewer2.org).

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]