R Graphics Cookbook Practical Recipes For Visualizing Data Chang instant download
R Graphics Cookbook Practical Recipes For Visualizing Data Chang instant download
https://ebookbell.com/product/r-graphics-cookbook-practical-
recipes-for-visualizing-data-chang-22122900
https://ebookbell.com/product/r-graphics-cookbook-chang-
winston-22122898
https://ebookbell.com/product/r-graphics-cookbook-winston-
chang-11866108
Graphic Design Cookbook Mix Match Recipes For Faster Better Layouts
Leonard Koren
https://ebookbell.com/product/graphic-design-cookbook-mix-match-
recipes-for-faster-better-layouts-leonard-koren-7386314
https://ebookbell.com/product/r-graphs-cookbook-hrishi-v-
mittal-2024350
R Graphs Cookbook Second Edition 2nd Edition Jaynal Abedin Hrishi V
Mittal
https://ebookbell.com/product/r-graphs-cookbook-second-edition-2nd-
edition-jaynal-abedin-hrishi-v-mittal-38439846
https://ebookbell.com/product/r-graphics-chapman-hallcrc-the-r-
series-1st-edition-murrell-55464902
https://ebookbell.com/product/r-graphics-second-edition-2nd-edition-
murrell-paul-5394834
https://ebookbell.com/product/r-graphics-third-edition-3rd-edition-
paul-murrell-7314672
https://ebookbell.com/product/r-graphics-2nd-edition-paul-
murrell-231845474
1. R Basics
1. 1.1. Installing a Package
2. 1.2. Loading a Package
3. 1.3. Loading a Delimited Text Data File
4. 1.4. Loading Data from an Excel File
5. 1.5. Loading Data from SPSS/SAS/Stata Files
2. Scatter Plots
1. 2.1. Making a Basic Scatter Plot
2. 2.2. Grouping Data Points by a Variable Using Shape or Color
3. 2.3. Using Different Point Shapes
4. 2.4. Mapping a Continuous Variable to Color or Size
5. 2.5. Dealing with Overplotting
6. 2.6. Adding Fitted Regression Model Lines
7. 2.7. Adding Fitted Lines from an Existing Model
8. 2.8. Adding Fitted Lines from Multiple Existing Models
9. 2.9. Adding Annotations with Model Coefficients
10. 2.10. Adding Marginal Rugs to a Scatter Plot
11. 2.11. Labeling Points in a Scatter Plot
12. 2.12. Creating a Balloon Plot
13. 2.13. Making a Scatter Plot Matrix
3. Summarized Data Distributions
1. 3.1. Making a Basic Histogram
2. 3.2. Making Multiple Histograms from Grouped Data
3. 3.3. Making a Density Curve
4. 3.4. Making Multiple Density Curves from Grouped Data
5. 3.5. Making a Frequency Polygon
6. 3.6. Making a Basic Box Plot
7. 3.7. Adding Notches to a Box Plot
8. 3.8. Adding Means to a Box Plot
9. 3.9. Making a Violin Plot
10. 3.10. Making a Dot Plot
11. 3.11. Making Multiple Dot Plots for Grouped Data
12. 3.12. Making a Density Plot of Two-Dimensional Data
R Graphics Cookbook
Second Edition
Winston Chang
R Graphics Cookbook
by Winston Chang
Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472.
O’Reilly books may be purchased for educational, business, or sales promotional use. Online
editions are also available for most titles (http://oreilly.com/safari). For more information,
contact our corporate/institutional sales department: 800-998-9938 or [email protected].
The O’Reilly logo is a registered trademark of O’Reilly Media, Inc. R Graphics Cookbook, the
cover image, and related trade dress are trademarks of O’Reilly Media, Inc.
While the publisher and the author have used good faith efforts to ensure that the information
and instructions contained in this work are accurate, the publisher and the author disclaim all
responsibility for errors or omissions, including without limitation responsibility for damages
resulting from the use of or reliance on this work. Use of the information and instructions
contained in this work is at your own risk. If any code samples or other technology this work
contains or describes is subject to open source licenses or the intellectual property rights of
others, it is your responsibility to ensure that your use thereof complies with such licenses and/or
rights.
978-1-491-97860-3
[LSI]
Chapter 1. R Basics
This chapter covers the basics: installing and using packages and loading data.
If you want to get started quickly, most of the recipes in this book require the ggplot2 and
gcookbook packages to be installed on your computer. To do this, run:
install.packages(c("ggplot2", "gcookbook"))
Then, in each R session, before running the examples in this book, you can load them with:
library(ggplot2)
library(gcookbook)
Note
Packages in R are collections of functions and/or data that are bundled up for easy distribution,
and installing a package will extend the functionality of R on your computer. If an R user creates
a package and thinks that it might be useful for others, that user can distribute it through a
package repository. The primary repository for distributing R packages is called CRAN (the
Comprehensive R Archive Network), but there are others, such as Bioconductor and Omegahat.
(1)
1.1 Installing a Package
(2)
Problem
You want to install a package from CRAN.
(3)
Solution
Use install.packages() and give it the name of the package you want to install. To install ggplot2,
run:
install.packages("ggplot2")
At this point you may be prompted to select a download mirror. It’s usually best to use the first
choice, https://cloud.r-project.org/, as it is a cloud-based mirror with endpoints all over the
world.
(4)
Discussion
When you tell R to install a package, it will automatically install any other packages that the first
package depends on.
(5)
1.2 Loading a Package
(6)
Problem
You want to load an installed package.
(7)
Solution
Use library() and give it the name of the package you want to install. To load ggplot2, run:
library(ggplot2)
(8)
Discussion
Most of the recipes in this book require loading a package before running the code, either for the
graphing capabilities (as in the ggplot2 package) or for example data sets (as in the MASS and
gcookbook packages).
One of R’s quirks is the package/library terminology. Although you use the library() function to
load a package, a package is not a library, and some longtime R users will get irate if you call it
that.
A library is a directory that contains a set of packages. You might, for example, have a system-
wide library as well as a library for each user.
(9)
1.3 Loading a Delimited Text Data File
(10)
Problem
You want to load data from a delimited text file.
(11)
Solution
The most common way to read in a file is to use comma-separated values (CSV) data:
data <- read.csv("datafile.csv")
(12)
Discussion
Since data files have many different formats, there are many options for loading them. For
example, if the data file does not have headers in the first row:
data <- read.csv("datafile.csv", header = FALSE)
The resulting data frame will have columns named V1, V2, and so on, and you will probably want
to rename them manually:
# Manually assign the header names
names(data) <- c("Column1", "Column2", "Column3")
You can set the delimiter with sep. If it is space-delimited, use sep = " ". If it is tab-delimited,
use \t, as in:
data <- read.csv("datafile.csv", sep = "\t")
By default, strings in the data are treated as factors. Suppose this is your data file, and you read it
in using read.csv():
"First","Last","Sex","Number"
"Currer","Bell","F",2
"Dr.","Seuss","M",49
"","Student",NA,21
The resulting data frame will store First and Last as factors, though it makes more sense in this
case to treat them as strings (or character vectors in R terminology). To differentiate this, use
stringsAsFactors=FALSE. If there are any columns that should be treated as factors, you can then
convert them individually:
data <- read.csv("datafile.csv", stringsAsFactors = FALSE)
# Convert to factor
data$Sex <- factor(data$Sex)
str(data)
#> 'data.frame': 3 obs. of 4 variables:
#> $ First : chr "Currer" "Dr." ""
#> $ Last : chr "Bell" "Seuss" "Student"
#> $ Sex : Factor w/ 2 levels "F","M": 1 2 NA
#> $ Number: int 2 49 21
Alternatively, you could load the file with strings as factors, and then convert individual columns
from factors to characters.
(13)
See Also
read.csv() is a convenience wrapper function around read.table(). If you need more control over
the input, see ?read.table.
(14)
1.4 Loading Data from an Excel File
(15)
Problem
You want to load data from an Excel file.
(16)
Solution
The readxl package has the function read_excel() for reading .xls and .xlsx files from Excel. This
will read the first sheet of an Excel spreadsheet:
# Only need to install once
install.packages("readxl")
library(readxl)
data <- read_excel("datafile.xlsx", 1)
(17)
Discussion
With read_excel(), you can load from other sheets by specifying a number for sheetIndex or a
name for sheetName:
data <- read_excel("datafile.xls", sheet = 2)
read_excel()uses the first row of the spreadsheet for column names. If you don’t want to use that
row for column names, use col_names = FALSE. The columns will instead be named X1, X2, and so
on.
By default, read_excel() will infer the type of each column, but if you want to specify the type of
each column, you can use the col_types argument. You can also drop columns if you specify the
type as "blank".
# Drop the first column, and specify the types of the next three columns
data <- read_excel("datafile.xls", col_types = c("blank", "text", "date", "numeric"))
(18)
See Also
See ?read_excel for more options controlling the reading of these files.
There are other packages for reading Excel files. The gdata package has a function read.xls() for
reading in .xls files, and the xlsx package has a function read.xlsx() for reading in .xlsx files.
They require external software to be installed on your computer: read.xls() requires Java, and
read.xlsx() requires Perl.
(19)
1.5 Loading Data from SPSS/SAS/Stata Files
(20)
Problem
You want to load data from a SPSS file, or from other programs like SAS or Stata.
(21)
Solution
The haven package has the function read_sav() for reading SPSS files. To load data from an
SPSS file:
# Only need to install the first time
install.packages("haven")
library(foreign)
data <- read_sav("datafile.sav")
(22)
Discussion
The haven package also includes functions to read from other formats:
read_sas(): SAS
read_dta(): Stata
An alternative to haven is the foreign package. It also supports SPSS and Stata files, but it is not
as up-to-date as the functions from haven. For example, it only supports Stata files up to version
12, while haven supports up to version 14 (the current version as of this writing).
(23)
See Also
Run ls("package:foreign") for a full list of functions in the foreign package.
(24)
Chapter 2. Scatter Plots
Scatter plots are used to display the relationship between two continuous variables. In a scatter
plot, each observation in a data set is represented by a point. Often, a scatter plot will also have a
line showing the predicted values based on some statistical model. This is easy to do with R and
ggplot2, and can help to make sense of data when the trends aren’t immediately obvious just by
looking at it.
With large data sets, it can be problematic to plot every single observation because the points
will be overplotted, obscuring one another. When this happens, you’ll probably want to
summarize the data before displaying it. We’ll also see how to do that in this chapter.
(25)
2.1 Making a Basic Scatter Plot
(26)
Problem
You want to make a scatter plot.
(27)
Solution
Use geom_point(), and map one variable to x and one to y.
In the heightweight data set, there are a number of columns, but we’ll only use two in this
example (Figure \@ref(fig:FIG-SCATTER-BASIC)):
library(gcookbook) # For the data set
# List the two columns we'll use
heightweight[, c("ageYear", "heightIn")]
#> ageYear heightIn
#> 1 11.92 56.3
#> 2 12.92 62.3
#> 3 12.75 63.3
#> 4 13.42 59.0
#> 5 15.92 62.5
#> 6 14.25 62.5
#> 7 15.42 59.0
#> 8 11.83 56.5
#> # ... with 228 more rows
(28)
Discussion
To use different shapes in a scatter plot, set the shape aesthetic. A common alternative to the
default solid circles (shape #19) is hollow ones (#21), as seen in Figure \@ref(fig:FIG-
SCATTER-BASIC-SHAPE-SIZE) (left):
ggplot(heightweight, aes(x = ageYear, y = heightIn)) + geom_point(shape = 21)
The size of the points can be controlled with the size aesthetic. The default value of size is 2. The
following will set size=1.5, for smaller points (Figure \@ref(fig:FIG-SCATTER-BASIC-
SHAPE-SIZE), right):
ggplot(heightweight, aes(x = ageYear, y = heightIn)) + geom_point(size = 1.5)
(29)
2.2 Grouping Data Points by a Variable
Using Shape or Color
(30)
Problem
You want to visually group points by some variable, using shape or color.
(31)
Solution
Map the grouping variable to shape or colour. In the heightweight data set, there are many
columns, but we’ll only use three of them in this example:
library(gcookbook) # For the data set
# Show the three columns we'll use
heightweight[, c("sex", "ageYear", "heightIn")]
#> sex ageYear heightIn
#> 1 f 11.92 56.3
#> 2 f 12.92 62.3
#> 3 f 12.75 63.3
#> 4 f 13.42 59.0
#> 5 f 15.92 62.5
#> 6 f 14.25 62.5
#> 7 f 15.42 59.0
#> 8 f 11.83 56.5
#> # ... with 228 more rows
We can group points on the variable sex, by mapping sex to one of the aesthetics colour or shape
(Figure \@ref(fig:FIG-SCATTER-SHAPE-COLOR)):
(32)
Discussion
The grouping variable must be categorical--in other words, a factor or character vector. If it is
stored as a vector of numeric values, it should be converted to a factor before it is used as a
grouping variable.
It is possible to map a variable to both shape and colour, or, if you have multiple grouping
variables, to map different variables to them. Here, we’ll map sex to shape and colour (Figure
\@ref(fig:FIG-SCATTER-SHAPE-COLOR-BOTH), left):
ggplot(heightweight, aes(x = ageYear, y = heightIn, shape = sex, colour = sex)) +
geom_point()
The default shapes and colors may not be very appealing. Other shapes can be used with
scale_shape_manual(), and other colors can be used with scale_colour_brewer() or
scale_colour_manual().
This will set different shapes and colors for the grouping variables (Figure \@ref(fig:FIG-
SCATTER-SHAPE-COLOR-BOTH), right):
ggplot(heightweight, aes(x = ageYear, y = heightIn, shape = sex, colour = sex)) +
geom_point() +
scale_shape_manual(values = c(1,2)) +
scale_colour_brewer(palette = "Set1")
(33)
(34)
See Also
To use different shapes, see Recipe \@ref(RECIPE-SCATTER-SHAPES).
(35)
2.3 Using Different Point Shapes
(36)
Problem
You want to use point shapes that are different from the defaults.
(37)
Solution
If you want to set the shape of all the points (Figure \@ref(fig:FIG-SCATTER-SHAPES)),
specify the shape in geom_point():
library(gcookbook) # For the data set
If you have mapped a variable to shape, use scale_shape_manual() to change the shapes:
# Use slightly larger points and use a shape scale with custom values
ggplot(heightweight, aes(x = ageYear, y = heightIn, shape = sex)) +
geom_point(size = 3) +
scale_shape_manual(values = c(1, 4))
(38)
Discussion
Figure \@ref(fig:FIG-SCATTER-SHAPES-CHART) shows the shapes that are available in R
graphics. Some of the point shapes (1–14) have just an outline, some (15–20) have just a solid
fill, and some (21–25) have an outline and fill that can be controlled separately. (You can also
use characters for points.)
For shapes 1–20, the color of the entire point -- even the points that are solid -- is controlled by
the colour aesthetic. For shapes 21–25, the outline is controlled by colour and the fill is controlled
by fill.
It’s possible to have the shape represent one variable and the fill (empty or solid) represent
another variable. This is done a little indirectly, by choosing shapes that have both colour and
fill, and a color palette that includes NA and another color (the NA will result in a hollow shape).
For example, we’ll take the heightweight data set and add another column that indicates whether
the child weighed 100 pounds or more (Figure \@ref(fig:FIG-SCATTER-SHAPES-FILL)):
# Make a copy of the data
hw <- heightweight
# Categorize into <100 and >=100 groups
hw$weightGroup <- cut(hw$weightLb, breaks = c(-Inf, 100, Inf),
labels = c("< 100", ">= 100"))
(39)
# Use shapes with fill and color, and use colors that are empty (NA) and
# filled
ggplot(hw, aes(x = ageYear, y = heightIn, shape = sex, fill = weightGroup)) +
geom_point(size = 2.5) +
scale_shape_manual(values = c(21, 24)) +
scale_fill_manual(values = c(NA, "black"),
guide = guide_legend(override.aes = list(shape = 21)))
(40)
See Also
For more on using different colors, see Chapter \@ref(CHAPTER-COLORS).
For more information about recoding a continuous variable to a categorical one, see Recipe
\@ref(RECIPE-DATAPREP-RECODE-CONTINUOUS).
(41)
2.4 Mapping a Continuous Variable to Color
or Size
(42)
Problem
You want to represent a third continuous variable using color or size.
(43)
Solution
Map the continuous variable to size or colour. In the heightweight data set, there are many
columns, but we’ll only use four of them in this example:
library(gcookbook) # For the data set
# List the four columns we'll use
heightweight[, c("sex", "ageYear", "heightIn", "weightLb")]
#> sex ageYear heightIn weightLb
#> 1 f 11.92 56.3 85.0
#> 2 f 12.92 62.3 105.0
#> 3 f 12.75 63.3 108.0
#> 4 f 13.42 59.0 92.0
#> 5 f 15.92 62.5 112.5
#> 6 f 14.25 62.5 112.0
#> 7 f 15.42 59.0 104.0
#> 8 f 11.83 56.5 69.0
#> # ... with 228 more rows
(44)
(45)
Exploring the Variety of Random
Documents with Different Content
I. Rise of the Freedom of the Open Sea
248. Former Claims to Control over the Sea 315
249. Practical Expression of claims to Maritime Sovereignty 317
250. Grotius's Attack on Maritime Sovereignty 318
251. Gradual recognition of the Freedom of the Open Sea 319
V. Piracy
272. Conception of Piracy 340
273. Private Ships as Subjects of Piracy 341
274. Mutinous Crew and Passengers as Subjects of Piracy 343
275. Object of Piracy 344
276. Piracy, how effected 344
277. Where Piracy can be committed 345
278. Jurisdiction over Pirates and their Punishment 345
279. Pirata non mutat dominium 346
280. Piracy according to Municipal Law 347
CHAPTER III
INDIVIDUALS
II. Nationality
293. Conception of Nationality 369
294. Function of Nationality 370
295. So-called Protégés and de facto Subjects 371
296. Nationality and Emigration 373
III. Modes of Acquiring and Losing Nationality
297. Five Modes of Acquisition of Nationality 374
298. Acquisition of Nationality by Birth 375
299. Acquisition of Nationality through Naturalisation 375
300. Acquisition of Nationality through Redintegration 376
301. Acquisition of Nationality through Subjugation and Cession 377
302. Seven Modes of losing Nationality 377
IX. Extradition
327. Extradition no legal duty 403
328. Extradition Treaties how arisen 404
329. Municipal Extradition Laws 405
330. Object of Extradition 407
331. Extraditable Crimes 408
332. Effectuation and Condition of Extradition 409
PART III
ORGANS OF THE STATES FOR THEIR INTERNATIONAL
RELATIONS
CHAPTER I
HEADS OF STATES AND FOREIGN OFFICES
II. Monarchs
346. Sovereignty of Monarchs 428
347. Consideration due to Monarchs at home 429
348. Consideration due to Monarchs abroad 429
349. The Retinue of Monarchs abroad 431
350. Monarchs travelling incognito 431
351. Deposed and Abdicated Monarchs 432
352. Regents 432
353. Monarchs in the service or subjects of Foreign Powers 432
CHAPTER II
DIPLOMATIC ENVOYS
CHAPTER III
CONSULS
CHAPTER IV
MISCELLANEOUS AGENCIES
V. International Offices
463. Character of International Offices 515
464. International Telegraph Offices 516
465. International Post Office 516
466. International Office of Weights and Measures 516
467. International Office for the Protection of Works of Literature and Art and of Industrial
Property 516
467a. The Pan-American Union 517
468. Maritime Office at Zanzibar and Bureau Spécial at Brussels 517
469. International Office of Customs Tariffs 517
470. Central Office of International Transports 517
471. Permanent Office of the Sugar Convention 517
471a. Agricultural Institute 518
471b. International Health Office 518
PART IV
INTERNATIONAL TRANSACTIONS
CHAPTER I
ON INTERNATIONAL TRANSACTIONS IN GENERAL
I. Negotiation
477. Conception of Negotiation 529
478. Parties to Negotiation 529
479. Purpose of Negotiation 530
480. Negotiations by whom conducted 531
481. Form of Negotiation 531
482. End and Effect of Negotiation 532
CHAPTER II
TREATIES
I. Character and Function of Treaties
491. Conception of Treaties 540
492. Different kinds of Treaties 540
493. Binding Force of Treaties 541
V. Ratification of Treaties
510. Conception and Function of Ratification 553
511. Rationale for the Institution of Ratification 554
512. Ratification regularly, but not absolutely, necessary 554
513. Length of Time for Ratification 555
514. Refusal of Ratification 556
515. Form of Ratification 557
516. Ratification by whom effected 558
517. Ratification cannot be partial and conditional 559
518. Effect of Ratification 561
VI. Effect of Treaties
519. Effect of Treaties upon Contracting Parties 561
520. Effect of Treaties upon the Subjects of the Parties 562
521. Effect of Changes in Government upon Treaties 562
522. Effect of Treaties upon Third States 563
X. Voidance of Treaties
540. Grounds of Voidance 576
541. Extinction of one of the two Contracting Parties 576
542. Impossibility of Execution 577
543. Realisation of Purpose of Treaty other than by Fulfilment 577
544. Extinction of such Object as was concerned in a Treaty 577
CHAPTER III
IMPORTANT GROUPS OF TREATIES
II. Alliances
569. Conception of Alliances 595
570. Parties to Alliances 597
571. Different kinds of Alliances 597
572. Conditions of Alliances 598
573. Casus Fœderis 599
INDEX 627
INTRODUCTION
FOUNDATION AND DEVELOPMENT OF THE
LAW OF NATIONS
CHAPTER I
FOUNDATION OF THE LAW OF NATIONS
I
THE LAW OF NATIONS AS LAW
Hall, pp. 14-16—Maine, pp. 50-53—Lawrence, §§ 1-3, and Essays, pp. 1-36—
Phillimore, I. §§ 1-12—Twiss, I. §§ 104-5—Taylor, § 2—Moore, I. §§ 1-2—Westlake,
I. pp. 1-13—Walker, History, I. §§ 1-8—Halleck, I. pp. 46-55—Ullmann, §§ 2-4—
Heffter, §§ 1-5—Holtzendorff in Holtzendorff, I. pp. 19-26—Nys, I. pp. 133-43—
Rivier, I. § 1—Bonfils, Nos. 26-31—Pradier-Fodéré, I. Nos. 1-24—Mérignhac, I. pp.
5-28—Martens, I. §§ 1-5—Fiore, I. Nos. 186-208, and Code, Nos. 1-26—Higgins,
"The Binding Force of International Law" (1910)—Pollock in The Law Quarterly
Review, XVIII. (1902), pp. 418-428—Scott in A.J. I. (1907), pp. 831-865—
Willoughby and Root in A.J. II. (1908), pp. 357-365 and 451-457.
Conception of the Law of Nations.
§ 1. Law of Nations or International Law (Droit des gens,
Völkerrecht) is the name for the body of customary and conventional
rules which are considered legally[1] binding by civilised States in
their intercourse with each other. Such part of these rules as is
binding upon all the civilised States without exception is called
universal International Law,[2] in contradistinction to particular
International Law, which is binding on two or a few States only. But
it is also necessary to distinguish general International Law. This
name must be given to the body of such rules as are binding upon a
great many States, including leading Powers. General International
Law, as, for instance, the Declaration of Paris of 1856, has a
tendency to become universal International Law.
[1] In contradistinction to mere usages and to rules of so-called International Comity,
see below §§ 9 and 19.
[2] The best example of universal International Law is the law connected with legation.
II
BASIS OF THE LAW OF NATIONS
ebookbell.com