Print examples of chapter 18 of 'R for Dummies'.

Description

To print a listing of all examples of a chapter, use ch18(). To run all the examples of ch18(), use example(ch18).

Usage

1
ch18()

See Also

toc

Other Chapters: ch01, ch02, ch03, ch04, ch05, ch06, ch07, ch08, ch09, ch10, ch11, ch12, ch13, ch14, ch15, ch16, ch17, ch19, ch20

Examples

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# Chapter 18 - Looking At ggplot2 Graphics

# Installing and Loading ggplot2

## Not run: 
install.packages("ggplot2")

## End(Not run)
library("ggplot2")

# Looking At Layers

ggplot(faithful, aes(x=eruptions, y=waiting)) + geom_point() + stat_smooth()

# Using Geoms and Stats

## Defining what data to use

## Mapping data to plot aesthetics

ggplot(faithful, aes(x=eruptions, y=waiting)) + geom_point() + stat_smooth()

## Getting geoms

### Creating a bar chart

ggplot(quakes, aes(x=depth)) + geom_bar()
# ggplot(quakes, aes(x=depth)) + geom_bar(binwidth=50) # <- Old version
ggplot(quakes, aes(x=depth)) + geom_histogram(binwidth=50) # <- with ggplot2 v2

quakes.agg <- aggregate(mag ~ round(depth, -1), data=quakes, FUN=length)
names(quakes.agg) <- c("depth", "mag")

ggplot(quakes.agg, aes(x=depth, y=mag)) +
   geom_bar(stat="identity")


### Making a scatterplot

ggplot(quakes, aes(x=long, y=lat)) + geom_point()


### Creating line charts

ggplot(longley, aes(x=Year, y=Unemployed)) + geom_line()


# Sussing Stats

## Binning data

# ggplot(quakes, aes(x=depth)) + geom_bar(binwidth=50)
ggplot(quakes, aes(x=depth)) + geom_histogram(binwidth=50)
ggplot(quakes, aes(x=depth)) + stat_bin(binwidth=50)

## Smoothing data

ggplot(longley, aes(x=Year, y=Employed)) + geom_point()

ggplot(longley, aes(x=Year, y=Employed)) +
   geom_point() + stat_smooth()

ggplot(longley, aes(x=Year, y=Employed)) +
   geom_point() + stat_smooth(method="lm")


# Adding Facets, Scales, and Options

## Adding facets

ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point()

ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point() +
   stat_smooth(method="lm") + facet_grid(~cyl)


ggplot(mtcars, aes(x=hp, y=mpg)) +
   geom_point(aes(shape=factor(cyl), colour=factor(cyl)))

ggplot(mtcars, aes(x=hp, y=mpg)) +
   geom_point(aes(shape=factor(cyl), colour=factor(cyl))) +
   scale_shape_discrete(name="Cylinders") +
   scale_colour_discrete(name="Cylinders")

## Changing options

ggplot(mtcars, aes(x=hp, y=mpg)) + geom_point(color="red") +
   xlab("Performance (horse power") +
   ylab("Fuel consumption (mpg)") +
   ggtitle("Motor car comparison")