18.2 Use components, annotation, and additional arguments in a plot
We have just seen some examples on how to make new components, what if we want to know more about existing components?
As an example the borders()
option function, provided by {ggplot2} to create a layer of map borders.
“A quick and dirty way to get map data (from the maps package) on to your plot.”
borders <- function(database = "world", regions = ".", fill = NA,
colour = "grey50", ...) {
df <- map_data(database, regions)
geom_polygon(
aes_(~long, ~lat, group = ~group),
data = df, fill = fill, colour = colour, ...,
inherit.aes = FALSE, show.legend = FALSE
)
}
library(maps)
data(us.cities)
capitals <- subset(us.cities, capital == 2)
ggplot(capitals, aes(long, lat)) +
borders("world", xlim = c(-130, -60), ylim = c(20, 50)) +
geom_point(aes(size = pop)) +
scale_size_area() +
coord_quickmap()
We can even add addtional arguments, such as those ones to modify and add things:
modifyList()
do.call()
geom_mean <- function(..., bar.params = list(), errorbar.params = list()) {
params <- list(...)
bar.params <- modifyList(params, bar.params)
errorbar.params <- modifyList(params, errorbar.params)
bar <- do.call("stat_summary", modifyList(
list(fun = "mean", geom = "bar", fill = "grey70"),
bar.params)
)
errorbar <- do.call("stat_summary", modifyList(
list(fun.data = "mean_cl_normal", geom = "errorbar", width = 0.4),
errorbar.params)
)
list(bar, errorbar)
}
And here is the result: