Graphics Reference
In-Depth Information
See Also
For more about overplotting, see
Dealing with Overplotting
.
Labeling Points in a Scatter Plot
Problem
You want to add labels to points in a scatter plot.
Solution
For annotating just one or a few points, you can use
annotate()
or
geom_text()
. For this ex-
ample, we'll use the
countries
data set and visualize the relationship between health expendit-
ures and infant mortality rate per 1,000 live births. To keep things manageable, we'll just take the
subset of countries that spent more than $2000 USD per capita:
library(gcookbook)
# For the data set
subset(countries, Year
==
2009
&
healthexp
>
2000
)
Name Code Year GDP laborrate healthexp infmortality
Andorra AND
2009
NA
NA
3089.636
3.1
Australia AUS
2009 42130.82
65.2 3867.429
4.2
Austria AUT
2009 45555.43
60.4 5037.311
3.6
...
United Kingdom GBR
2009 35163.41
62.2 3285.050
4.7
United States USA
2009 45744.56
65.0 7410.163
6.6
We'll save the basic scatter plot object in
sp
and add then add things to it. To manually add
require some trial-and-error tweaking to get them positioned just right:
sp
<-
ggplot(subset(countries, Year
==
2009
&
healthexp
>
2000
),
aes(x
=
healthexp, y
=
infmortality))
+
geom_point()
sp
+
annotate(
"text"
, x
=
4350
, y
=
5.4
, label
=
"Canada"
)
+
annotate(
"text"
, x
=
7400
, y
=
6.8
, label
=
"USA"
)