Title: | Streamlined Plot Theme and Plot Annotations for 'ggplot2' |
---|---|
Description: | Provides various features that help with creating publication-quality figures with 'ggplot2', such as a set of themes, functions to align plots and arrange them into complex compound figures, and functions that make it easy to annotate plots and or mix plots with images. The package was originally written for internal use in the Wilke lab, hence the name (Claus O. Wilke's plot package). It has also been used extensively in the book Fundamentals of Data Visualization. |
Authors: | Claus O. Wilke [aut, cre] |
Maintainer: | Claus O. Wilke <[email protected]> |
License: | GPL-2 |
Version: | 1.1.3.9000 |
Built: | 2024-10-31 16:34:13 UTC |
Source: | https://github.com/wilkelab/cowplot |
This function can add an arbitrary label or mathematical expression underneath
the plot, similar to the sub
parameter in base R. It is mostly superseded now by the
caption
argument to ggplot2::labs()
, and it is recommended to use caption
instead of
add_sub()
whenever possible.
add_sub( plot, label, x = 0.5, y = 0.5, hjust = 0.5, vjust = 0.5, vpadding = grid::unit(1, "lines"), fontfamily = "", fontface = "plain", color = "black", size = 14, angle = 0, lineheight = 0.9, colour )
add_sub( plot, label, x = 0.5, y = 0.5, hjust = 0.5, vjust = 0.5, vpadding = grid::unit(1, "lines"), fontfamily = "", fontface = "plain", color = "black", size = 14, angle = 0, lineheight = 0.9, colour )
plot |
A ggplot object or gtable object derived from a ggplot object. |
label |
The label with which the plot should be annotated. Can be a plotmath expression. |
x |
The x position of the label |
y |
The y position of the label |
hjust |
Horizontal justification |
vjust |
Vertical justification |
vpadding |
Vertical padding. The total vertical space added to the label, given in grid units. By default, this is added equally above and below the label. However, by changing the y and vjust parameters, this can be changed. |
fontfamily |
The font family |
fontface |
The font face ("plain", "bold", etc.) |
color , colour
|
Text color |
size |
Point size of text |
angle |
Angle at which text is drawn |
lineheight |
Line height of text |
The exact location where the
label is placed is controlled by the parameters x
, y
, hjust
, and
vjust
. By default, all these parameters are set to 0.5, which places the label
centered underneath the plot panel. A value of x = 0
indicates the left boundary
of the plot panel and a value of x = 1
indicates the right boundary. The parameter
hjust
works just as elsewhere in ggplot2. Thus, x = 0, hjust = 0
places
the label left-justified at the left boundary of the plot panel, x = 0.5, hjust = 0.5
places the label centered underneath the plot panel, and x = 1, hjust = 1
places
it right-justified at the right boundary of the plot panel. x
-values below 0 or
above 1 are allowed, and they move the label beyond the limits of the plot panel.
The y
coordinates are relative to the added vertical space that is introduced
underneath the x-axis label to place the annotation. A value of y=0
indicates
the bottom-most edge of that space and a value of y=1
indicates the top-most
edge of that space. The total height of the added space is given by the height needed
to draw the label plus the value of vpadding
. Thus, if y=0, vjust=0
then
the extra padding is added entirely above the label, if y=1, vjust=1
then the
extra padding is added entirely below the label, and if y=0.5, vjust=0.5
(the
default) then the extra padding is added equally above and below the label. As is the
case with x
, y
-values outside the range 0-1 are allowed. In particular,
for sufficiently large values of y
, the label will eventually be located inside
the plot panel.
A gtable object holding the modified plot.
library(ggplot2) theme_set(theme_half_open()) p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") + background_grid(minor='none') ggdraw(add_sub(p1, "This is an annotation.\nAnnotations can span multiple lines.")) # You can also do this repeatedly. p2 <- add_sub(p1, "This formula has no relevance here:", y = 0, vjust = 0) p3 <- add_sub(p2, expression(paste(a^2+b^2, " = ", c^2))) ggdraw(p3) #This code also works with faceted plots: plot.iris <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_grid(. ~ Species) + stat_smooth(method = "lm") + background_grid(major = 'y', minor = "none") + # add thin horizontal lines panel_border() # and a border around each panel p2 <- add_sub(plot.iris, "Annotation underneath a faceted plot, left justified.", x = 0, hjust = 0) ggdraw(p2) # Finally, it is possible to move the annotation inside of the plot if desired. ggdraw(add_sub(p1, "Annotation inside plot", vpadding=grid::unit(0, "lines"), y = 6, x = 0.03, hjust = 0))
library(ggplot2) theme_set(theme_half_open()) p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line(colour = "blue") + background_grid(minor='none') ggdraw(add_sub(p1, "This is an annotation.\nAnnotations can span multiple lines.")) # You can also do this repeatedly. p2 <- add_sub(p1, "This formula has no relevance here:", y = 0, vjust = 0) p3 <- add_sub(p2, expression(paste(a^2+b^2, " = ", c^2))) ggdraw(p3) #This code also works with faceted plots: plot.iris <- ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + facet_grid(. ~ Species) + stat_smooth(method = "lm") + background_grid(major = 'y', minor = "none") + # add thin horizontal lines panel_border() # and a border around each panel p2 <- add_sub(plot.iris, "Annotation underneath a faceted plot, left justified.", x = 0, hjust = 0) ggdraw(p2) # Finally, it is possible to move the annotation inside of the plot if desired. ggdraw(add_sub(p1, "Annotation inside plot", vpadding=grid::unit(0, "lines"), y = 6, x = 0.03, hjust = 0))
Align the plot area of multiple plots. Inputs are a list of plots plus alignment parameters.
Horizontal or vertical alignment or both are possible. In the simplest case the function will align all
elements of each plot, but it can handle more complex cases as long as the axis parameter is defined. In this case,
alignment is done through a call to align_margin()
. The function align_plots
is called by the plot_grid()
function
and is usually not called directly, though direct calling of the function is useful if plots with
multiple y-axes are desired (see example).
align_plots( ..., plotlist = NULL, align = c("none", "h", "v", "hv"), axis = c("none", "l", "r", "t", "b", "lr", "tb", "tblr"), greedy = TRUE )
align_plots( ..., plotlist = NULL, align = c("none", "h", "v", "hv"), axis = c("none", "l", "r", "t", "b", "lr", "tb", "tblr"), greedy = TRUE )
... |
List of plots to be aligned. |
plotlist |
(optional) List of plots to display. Alternatively, the plots can be provided individually as the first n arguments of the function align_plots (see plot_grid examples). |
align |
(optional) Specifies whether graphs in the grid should be horizontally ("h") or
vertically ("v") aligned. Options are |
axis |
(optional) Specifies whether graphs should be aligned by the left ("l"), right ("r"), top ("t"), or bottom ("b")
margins. Options are |
greedy |
(optional) Defines the alignment policy when alignment axes are specified via the
|
library(ggplot2) p1 <- ggplot(mpg, aes(manufacturer, hwy)) + stat_summary(fun.y="median", geom = "bar") + theme_half_open() + theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust= 1)) p2 <- ggplot(mpg, aes(manufacturer, displ)) + geom_point(color="red") + scale_y_continuous(position = "right") + theme_half_open() + theme(axis.text.x = element_blank()) # manually align and plot on top of each other aligned_plots <- align_plots(p1, p2, align="hv", axis="tblr") # Note: In most cases two y-axes should not be used, but this example # illustrates how one could accomplish it. ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])
library(ggplot2) p1 <- ggplot(mpg, aes(manufacturer, hwy)) + stat_summary(fun.y="median", geom = "bar") + theme_half_open() + theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust= 1)) p2 <- ggplot(mpg, aes(manufacturer, displ)) + geom_point(color="red") + scale_y_continuous(position = "right") + theme_half_open() + theme(axis.text.x = element_blank()) # manually align and plot on top of each other aligned_plots <- align_plots(p1, p2, align="hv", axis="tblr") # Note: In most cases two y-axes should not be used, but this example # illustrates how one could accomplish it. ggdraw(aligned_plots[[1]]) + draw_plot(aligned_plots[[2]])
This function does its best attempt to take whatever you provide it and turn it into a grob. It is primarily meant to convert ggplot plots into grobs, but it will also take any grid object (grob), a recorded base R plot, a formula specifying a base R plot, a function that generates a base R plot, or a trellis object.
as_grob(plot, device = NULL)
as_grob(plot, device = NULL)
plot |
The plot to convert |
device |
A function that creates an appropriate null device. See |
library(grid) x <- 1:10 y <- (1:10)^2 p <- ~plot(x, y) grid.newpage() grid.draw(as_grob(p))
library(grid) x <- 1:10 y <- (1:10)^2 p <- ~plot(x, y) grid.newpage() grid.draw(as_grob(p))
This function does its best attempt to take whatever you provide it and turn it into a gtable. It is primarily meant to convert ggplot plots into gtables, but it will also take any grid object (grob), a recorded R base plot, or a function that generates an R base plot.
as_gtable(plot) plot_to_gtable(plot)
as_gtable(plot) plot_to_gtable(plot)
plot |
The plot or other graphics object to convert into a gtable. Here, |
To convert ggplot plots, the function needs to use a null graphics device. This can be set
with set_null_device()
.
This function takes an existing ggplot2 plot and copies one or both of the axis into a new plot.
The main idea is to use this in conjunction with insert_xaxis_grob()
or insert_yaxis_grob()
to
draw custom axis-like objects or margin annotations. Importantly, while this function works for
both continuous and discrete scales, notice that discrete scales are converted into continuous scales
in the returned axis canvas. The levels of the discrete scale are placed at continuous values of
1, 2, 3, etc. See Examples for an example of how to convert a discrete scale into a continuous
scale.
axis_canvas( plot, axis = "y", data = NULL, mapping = aes(), xlim = NULL, ylim = NULL, coord_flip = FALSE )
axis_canvas( plot, axis = "y", data = NULL, mapping = aes(), xlim = NULL, ylim = NULL, coord_flip = FALSE )
plot |
The plot defining the x and/or y axis range for the axis canvas. |
axis |
Specifies which axis to copy from |
data |
(optional) Data to be displayed in this layer. |
mapping |
(optional) Aesthetic mapping to be used in this layer. |
xlim |
(optional) Vector of two numbers specifying the limits of the x axis. Ignored
if the x axis is copied over from |
ylim |
(optional) Vector of two numbers specifying the limits of the y axis. Ignored
if the y axis is copied over from |
coord_flip |
(optional) If |
# annotate line graphs with labels on the right library(dplyr) library(tidyr) library(ggplot2) theme_set(theme_half_open()) x <- seq(0, 10, .1) d <- data.frame(x, linear = x, squared = x*x/5, cubed = x*x*x/25) %>% gather(fun, y, -x) pmain <- ggplot(d, aes(x, y, group = fun)) + geom_line() + scale_x_continuous(expand = c(0, 0)) paxis <- axis_canvas(pmain, axis = "y") + geom_text(data = filter(d, x == max(x)), aes(y = y, label = paste0(" ", fun)), x = 0, hjust = 0, vjust = 0.5) ggdraw(insert_yaxis_grob(pmain, paxis, grid::unit(.25, "null"))) # discrete scale with integrated color legend pmain <- ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + geom_violin(trim = FALSE) + guides(fill = "none") + scale_x_discrete(labels = NULL) + theme_minimal() label_data <- data.frame(x = 1:nlevels(iris$Species), Species = levels(iris$Species)) paxis <- axis_canvas(pmain, axis = "x", data = label_data, mapping = aes(x = x)) + geom_tile(aes(fill = Species, y = 0.5), width = 0.9, height = 0.3) + geom_text(aes(label = Species, y = 0.5), hjust = 0.5, vjust = 0.5, size = 11/.pt) ggdraw(insert_xaxis_grob(pmain, paxis, grid::unit(.07, "null"), position = "bottom")) # add marginal density distributions to plot pmain <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) + geom_point() xdens <- axis_canvas(pmain, axis = "x") + geom_density(data=iris, aes(x=Sepal.Length, fill=Species), alpha=0.7, size=.2) # need to set `coord_flip = TRUE` if you plan to use `coord_flip()` ydens <- axis_canvas(pmain, axis = "y", coord_flip = TRUE) + geom_density(data=iris, aes(x=Sepal.Width, fill=Species), alpha=0.7, size=.2) + coord_flip() p1 <- insert_xaxis_grob(pmain, xdens, grid::unit(.2, "null"), position = "top") p2 <- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right") ggdraw(p2)
# annotate line graphs with labels on the right library(dplyr) library(tidyr) library(ggplot2) theme_set(theme_half_open()) x <- seq(0, 10, .1) d <- data.frame(x, linear = x, squared = x*x/5, cubed = x*x*x/25) %>% gather(fun, y, -x) pmain <- ggplot(d, aes(x, y, group = fun)) + geom_line() + scale_x_continuous(expand = c(0, 0)) paxis <- axis_canvas(pmain, axis = "y") + geom_text(data = filter(d, x == max(x)), aes(y = y, label = paste0(" ", fun)), x = 0, hjust = 0, vjust = 0.5) ggdraw(insert_yaxis_grob(pmain, paxis, grid::unit(.25, "null"))) # discrete scale with integrated color legend pmain <- ggplot(iris, aes(x = Species, y = Sepal.Length, fill = Species)) + geom_violin(trim = FALSE) + guides(fill = "none") + scale_x_discrete(labels = NULL) + theme_minimal() label_data <- data.frame(x = 1:nlevels(iris$Species), Species = levels(iris$Species)) paxis <- axis_canvas(pmain, axis = "x", data = label_data, mapping = aes(x = x)) + geom_tile(aes(fill = Species, y = 0.5), width = 0.9, height = 0.3) + geom_text(aes(label = Species, y = 0.5), hjust = 0.5, vjust = 0.5, size = 11/.pt) ggdraw(insert_xaxis_grob(pmain, paxis, grid::unit(.07, "null"), position = "bottom")) # add marginal density distributions to plot pmain <- ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width, color=Species)) + geom_point() xdens <- axis_canvas(pmain, axis = "x") + geom_density(data=iris, aes(x=Sepal.Length, fill=Species), alpha=0.7, size=.2) # need to set `coord_flip = TRUE` if you plan to use `coord_flip()` ydens <- axis_canvas(pmain, axis = "y", coord_flip = TRUE) + geom_density(data=iris, aes(x=Sepal.Width, fill=Species), alpha=0.7, size=.2) + coord_flip() p1 <- insert_xaxis_grob(pmain, xdens, grid::unit(.2, "null"), position = "top") p2 <- insert_yaxis_grob(p1, ydens, grid::unit(.2, "null"), position = "right") ggdraw(p2)
This function provides a simple way to set the background grid in ggplot2. It
doesn't do anything that can't be done just the same with theme()
. However, it simplifies
creation of the most commonly needed variations.
background_grid( major = c("xy", "x", "y", "only_minor", "none"), minor = c("none", "xy", "x", "y"), size.major = 0.5, size.minor = 0.2, color.major = "grey85", color.minor = "grey85", colour.major, colour.minor )
background_grid( major = c("xy", "x", "y", "only_minor", "none"), minor = c("none", "xy", "x", "y"), size.major = 0.5, size.minor = 0.2, color.major = "grey85", color.minor = "grey85", colour.major, colour.minor )
major |
Specifies along which axes you would like to plot major grid lines. Options are "xy", "x", "y", "none". |
minor |
Specifies along which axes you would like to plot minor grid lines. Options are "xy", "x", "y", "none". |
size.major |
Size of the major grid lines. |
size.minor |
Size of the minor grid lines. |
color.major , colour.major
|
Color of the major grid lines. |
color.minor , colour.minor
|
Color of the minor grid lines. |
Note: This function completely overwrites all background grid settings of the current theme. If that
is not what you want, you may be better off using theme()
directly.
library(ggplot2) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + theme_half_open() + background_grid()
library(ggplot2) ggplot(iris, aes(Sepal.Length, Sepal.Width)) + geom_point() + theme_half_open() + background_grid()
The main purpose of this function is to add labels specifying extra information about
the figure, such as "Figure 1", or "A" - often useful in cowplots with more than
one pane. The function is similar to draw_plot_label
.
draw_figure_label( label, position = c("top.left", "top", "top.right", "bottom.left", "bottom", "bottom.right"), size, fontface, ... )
draw_figure_label( label, position = c("top.left", "top", "top.right", "bottom.left", "bottom", "bottom.right"), size, fontface, ... )
label |
Label to be drawn |
position |
Position of the label, can be one of "top.left", "top", "top.right", "bottom.left", "bottom", "bottom.right". Default is "top.left" |
size |
(optional) Size of the label to be drawn. Default is the text size of the current theme |
fontface |
(optional) Font face of the label to be drawn. Default is the font face of the current theme |
... |
other arguments passed to |
Ulrik Stervbo (ulrik.stervbo @ gmail.com)
library(ggplot2) df <- data.frame( x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4 ) p1 <- ggplot(df, aes(x, y1)) + geom_point() p2 <- ggplot(df, aes(x, y2)) + geom_point() p3 <- ggplot(df, aes(x, y3)) + geom_point() p4 <- ggplot(df, aes(x, y4)) + geom_point() # Create a simple grid p <- plot_grid(p1, p2, p3, p4, align = 'hv') # Default font size and position p + draw_figure_label(label = "Figure 1") # Different position and font size p + draw_figure_label(label = "Figure 1", position = "bottom.right", size = 10) # Using bold font face p + draw_figure_label(label = "Figure 1", fontface = "bold") # Making the label red and slanted p + draw_figure_label(label = "Figure 1", angle = -45, colour = "red") # Labeling an individual plot ggdraw(p2) + draw_figure_label(label = "Figure 1", position = "bottom.right", size = 10)
library(ggplot2) df <- data.frame( x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4 ) p1 <- ggplot(df, aes(x, y1)) + geom_point() p2 <- ggplot(df, aes(x, y2)) + geom_point() p3 <- ggplot(df, aes(x, y3)) + geom_point() p4 <- ggplot(df, aes(x, y4)) + geom_point() # Create a simple grid p <- plot_grid(p1, p2, p3, p4, align = 'hv') # Default font size and position p + draw_figure_label(label = "Figure 1") # Different position and font size p + draw_figure_label(label = "Figure 1", position = "bottom.right", size = 10) # Using bold font face p + draw_figure_label(label = "Figure 1", fontface = "bold") # Making the label red and slanted p + draw_figure_label(label = "Figure 1", angle = -45, colour = "red") # Labeling an individual plot ggdraw(p2) + draw_figure_label(label = "Figure 1", position = "bottom.right", size = 10)
Places an arbitrary grob somewhere onto the drawing canvas. By default, coordinates run from 0 to 1, and the point (0, 0) is in the lower left corner of the canvas.
draw_grob( grob, x = 0, y = 0, width = 1, height = 1, scale = 1, clip = "inherit", hjust = 0, vjust = 0, halign = 0.5, valign = 0.5 )
draw_grob( grob, x = 0, y = 0, width = 1, height = 1, scale = 1, clip = "inherit", hjust = 0, vjust = 0, halign = 0.5, valign = 0.5 )
grob |
The grob to place. |
x |
The x location of the grob. (Left side if |
y |
The y location of the grob. (Bottom side if |
width |
Width of the grob. |
height |
Height of the grob. |
scale |
Scales the grob relative to the rectangle defined by |
clip |
Set to "on" to clip the grob or "inherit" to not clip. Note that clipping doesn't always work as expected, due to limitations of the grid graphics system. |
hjust , vjust
|
Horizontal and vertical justification relative to x. |
halign , valign
|
Horizontal and vertical justification of the grob inside the box. |
# A grid grob (here a blue circle) g <- grid::circleGrob(gp = grid::gpar(fill = "blue")) # place into the middle of the plotting area, at a scale of 50% ggdraw() + draw_grob(g, scale = 0.5)
# A grid grob (here a blue circle) g <- grid::circleGrob(gp = grid::gpar(fill = "blue")) # place into the middle of the plotting area, at a scale of 50% ggdraw() + draw_grob(g, scale = 0.5)
Places an image somewhere onto the drawing canvas. By default, coordinates run from
0 to 1, and the point (0, 0) is in the lower left corner of the canvas. Requires the magick
package to work, and fails gracefully if that package is not installed.
draw_image( image, x = 0, y = 0, width = 1, height = 1, scale = 1, clip = "inherit", interpolate = TRUE, hjust = 0, vjust = 0, halign = 0.5, valign = 0.5 )
draw_image( image, x = 0, y = 0, width = 1, height = 1, scale = 1, clip = "inherit", interpolate = TRUE, hjust = 0, vjust = 0, halign = 0.5, valign = 0.5 )
image |
The image to place. Can be a file path, a URL, or a raw vector with image data,
as in |
x |
The x location of the image. (Left side if |
y |
The y location of the image. (Bottom side if |
width |
Width of the image. |
height |
Height of the image. |
scale |
Scales the image relative to the rectangle defined by |
clip |
Set to "on" to clip the image relative to the box into which it is draw (useful for |
interpolate |
A logical value indicating whether to linearly interpolate the image (the alternative is to use nearest-neighbour interpolation, which gives a more blocky result). |
hjust , vjust
|
Horizontal and vertical justification relative to x. |
halign , valign
|
Horizontal and vertical justification of the image inside the box. |
library(ggplot2) # Use image as plot background p <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) + geom_density(alpha = 0.7) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_half_open(12) logo_file <- system.file("extdata", "logo.png", package = "cowplot") ggdraw() + draw_image( logo_file, scale = .7 ) + draw_plot(p) # Place in lower right corner ggdraw() + draw_image( logo_file, scale = .3, x = 1, hjust = 1, halign = 1, valign = 0 ) + draw_plot(p) ## Not run: # Make grid with plot and image cow_file <- system.file("extdata", "cow.jpg", package = "cowplot") p2 <- ggdraw() + draw_image(cow_file, scale = 0.9) plot_grid( p + theme(legend.position = c(1, 1), legend.justification = c(1, 1)), p2, labels = "AUTO" ) # Manipulate images and draw in plot coordinates if (requireNamespace("magick", quietly = TRUE)){ img <- magick::image_transparent( magick::image_read(logo_file), color = "white" ) img2 <- magick::image_negate(img) ggplot(data.frame(x = 1:3, y = 1:3), aes(x, y)) + geom_point(size = 3) + geom_abline(slope = 1, intercept = 0, linetype = 2, color = "blue") + draw_image(img , x = 1, y = 1, scale = .9) + draw_image(img2, x = 2, y = 2, scale = .9) } ## End(Not run)
library(ggplot2) # Use image as plot background p <- ggplot(iris, aes(x = Sepal.Length, fill = Species)) + geom_density(alpha = 0.7) + scale_y_continuous(expand = expansion(mult = c(0, 0.05))) + theme_half_open(12) logo_file <- system.file("extdata", "logo.png", package = "cowplot") ggdraw() + draw_image( logo_file, scale = .7 ) + draw_plot(p) # Place in lower right corner ggdraw() + draw_image( logo_file, scale = .3, x = 1, hjust = 1, halign = 1, valign = 0 ) + draw_plot(p) ## Not run: # Make grid with plot and image cow_file <- system.file("extdata", "cow.jpg", package = "cowplot") p2 <- ggdraw() + draw_image(cow_file, scale = 0.9) plot_grid( p + theme(legend.position = c(1, 1), legend.justification = c(1, 1)), p2, labels = "AUTO" ) # Manipulate images and draw in plot coordinates if (requireNamespace("magick", quietly = TRUE)){ img <- magick::image_transparent( magick::image_read(logo_file), color = "white" ) img2 <- magick::image_negate(img) ggplot(data.frame(x = 1:3, y = 1:3), aes(x, y)) + geom_point(size = 3) + geom_abline(slope = 1, intercept = 0, linetype = 2, color = "blue") + draw_image(img , x = 1, y = 1, scale = .9) + draw_image(img2, x = 2, y = 2, scale = .9) } ## End(Not run)
This function can draw either a character string or mathematical expression at the given
coordinates. It works both on top of ggdraw
and directly with ggplot
, depending
on which coordinate system is desired (see examples).
draw_label( label, x = 0.5, y = 0.5, hjust = 0.5, vjust = 0.5, fontfamily = "", fontface = "plain", color = "black", size = 14, angle = 0, lineheight = 0.9, alpha = 1, colour )
draw_label( label, x = 0.5, y = 0.5, hjust = 0.5, vjust = 0.5, fontfamily = "", fontface = "plain", color = "black", size = 14, angle = 0, lineheight = 0.9, alpha = 1, colour )
label |
String or plotmath expression to be drawn. |
x |
The x location (origin) of the label. |
y |
The y location (origin) of the label. |
hjust |
Horizontal justification. Default = 0.5 (centered on x). 0 = flush-left at x, 1 = flush-right. |
vjust |
Vertical justification. Default = 0.5 (centered on y). 0 = baseline at y, 1 = ascender at y. |
fontfamily |
The font family |
fontface |
The font face ("plain", "bold", etc.) |
color , colour
|
Text color |
size |
Point size of text |
angle |
Angle at which text is drawn |
lineheight |
Line height of text |
alpha |
The alpha value of the text |
By default, the x and y coordinates specify the center of the text box. Set hjust = 0, vjust = 0
to specify
the lower left corner, and other values of hjust
and vjust
for any other relative location you want to
specify.
library(ggplot2) # setup plot and a label (regression description) p <- ggplot(mtcars, aes(disp, mpg)) + geom_line(color = "blue") + theme_half_open() + background_grid(minor = 'none') out <- cor.test(mtcars$disp, mtcars$mpg, method = 'sp', exact = FALSE) label <- substitute( paste("Spearman ", rho, " = ", estimate, ", P = ", pvalue), list(estimate = signif(out$estimate, 2), pvalue = signif(out$p.value, 2)) ) # Add label to plot, centered on {x,y} (in data coordinates) p + draw_label(label, x = 300, y = 32) # Add label to plot in data coordinates, flush-left at x, baseline at y. p + draw_label(label, x = 100, y = 30, hjust = 0, vjust = 0) # Add labels via ggdraw. Uses ggdraw coordinates. # ggdraw coordinates default to xlim = c(0, 1), ylim = c(0, 1). ggdraw(p) + draw_label("centered on 70% of x range,\n90% of y range", x = 0.7, y = 0.9) ggdraw(p) + draw_label("bottom left at (0, 0)", x = 0, y = 0, hjust = 0, vjust = 0) + draw_label("top right at (1, 1)", x = 1, y = 1, hjust = 1, vjust = 1) + draw_label("centered on (0.5, 0.5)", x = 0.5, y = 0.5, hjust = 0.5, vjust = 0.5)
library(ggplot2) # setup plot and a label (regression description) p <- ggplot(mtcars, aes(disp, mpg)) + geom_line(color = "blue") + theme_half_open() + background_grid(minor = 'none') out <- cor.test(mtcars$disp, mtcars$mpg, method = 'sp', exact = FALSE) label <- substitute( paste("Spearman ", rho, " = ", estimate, ", P = ", pvalue), list(estimate = signif(out$estimate, 2), pvalue = signif(out$p.value, 2)) ) # Add label to plot, centered on {x,y} (in data coordinates) p + draw_label(label, x = 300, y = 32) # Add label to plot in data coordinates, flush-left at x, baseline at y. p + draw_label(label, x = 100, y = 30, hjust = 0, vjust = 0) # Add labels via ggdraw. Uses ggdraw coordinates. # ggdraw coordinates default to xlim = c(0, 1), ylim = c(0, 1). ggdraw(p) + draw_label("centered on 70% of x range,\n90% of y range", x = 0.7, y = 0.9) ggdraw(p) + draw_label("bottom left at (0, 0)", x = 0, y = 0, hjust = 0, vjust = 0) + draw_label("top right at (1, 1)", x = 1, y = 1, hjust = 1, vjust = 1) + draw_label("centered on (0.5, 0.5)", x = 0.5, y = 0.5, hjust = 0.5, vjust = 0.5)
Provide a sequence of x values and accompanying y values to draw a line on a plot.
draw_line(x, y, ...)
draw_line(x, y, ...)
x |
Vector of x coordinates. |
y |
Vector of y coordinates. |
... |
geom_path parameters such as |
This is a convenience function, providing a wrapper around ggplot2's geom_path
.
ggdraw() + draw_line( x = c(0.2, 0.7, 0.7, 0.3), y = c(0.1, 0.3, 0.9, 0.8), color = "blue", size = 2 )
ggdraw() + draw_line( x = c(0.2, 0.7, 0.7, 0.3), y = c(0.1, 0.3, 0.9, 0.8), color = "blue", size = 2 )
Places a plot somewhere onto the drawing canvas. By default, coordinates run from 0 to 1, and the point (0, 0) is in the lower left corner of the canvas.
draw_plot( plot, x = 0, y = 0, width = 1, height = 1, scale = 1, hjust = 0, vjust = 0, halign = 0.5, valign = 0.5 )
draw_plot( plot, x = 0, y = 0, width = 1, height = 1, scale = 1, hjust = 0, vjust = 0, halign = 0.5, valign = 0.5 )
plot |
The plot to place. Can be a ggplot2 plot, an arbitrary grob or gtable,
or a recorded base-R plot, as in |
x |
The x location of the plot. (Left side if |
y |
The y location of the plot. (Bottom side if |
width |
Width of the plot. |
height |
Height of the plot. |
scale |
Scales the grob relative to the rectangle defined by |
hjust , vjust
|
Horizontal and vertical justification relative to x. |
halign , valign
|
Horizontal and vertical justification of the plot inside the box. |
library(ggplot2) # make a plot p <- ggplot(data.frame(x = 1:3, y = 1:3), aes(x, y)) + geom_point() # draw into the top-right corner of a larger plot area ggdraw() + draw_plot(p, .6, .6, .4, .4)
library(ggplot2) # make a plot p <- ggplot(data.frame(x = 1:3, y = 1:3), aes(x, y)) + geom_point() # draw into the top-right corner of a larger plot area ggdraw() + draw_plot(p, .6, .6, .4, .4)
This function adds a plot label to the upper left corner of a graph (or an arbitrarily specified position). It takes all the same parameters
as draw_text
, but has defaults that make it convenient to label graphs with letters A, B, C, etc. Just like draw_text()
,
it can handle vectors of labels with associated coordinates.
draw_plot_label( label, x = 0, y = 1, hjust = -0.5, vjust = 1.5, size = 16, fontface = "bold", family = NULL, color = NULL, colour, ... )
draw_plot_label( label, x = 0, y = 1, hjust = -0.5, vjust = 1.5, size = 16, fontface = "bold", family = NULL, color = NULL, colour, ... )
label |
String (or vector of strings) to be drawn as the label. |
x |
The x position (or vector thereof) of the label(s). |
y |
The y position (or vector thereof) of the label(s). |
hjust |
Horizontal adjustment. |
vjust |
Vertical adjustment. |
size |
Font size of the label to be drawn. |
fontface |
Font face of the label to be drawn. |
family |
(optional) Font family of the plot labels. If not provided, is taken from the current theme. |
color , colour
|
(optional) Color of the plot labels. If not provided, is taken from the current theme. |
... |
Other arguments to be handed to |
This is a convenience function to plot multiple pieces of text at the same time. It cannot
handle mathematical expressions, though. For those, use draw_label
.
draw_text(text, x = 0.5, y = 0.5, size = 14, hjust = 0.5, vjust = 0.5, ...)
draw_text(text, x = 0.5, y = 0.5, size = 14, hjust = 0.5, vjust = 0.5, ...)
text |
A vector of Character (not expressions) specifying the string(s) to be written. |
x |
Vector of x coordinates. |
y |
Vector of y coordinates. |
size |
Font size of the text to be drawn. |
hjust |
(default = 0.5) |
vjust |
(default = 0.5) |
... |
Style parameters, such as |
Note that font sizes are scaled by a factor of 2.85, so sizes agree with those of
the theme. This is different from geom_text
in ggplot2.
By default, the x and y coordinates specify the center of the text box. Set hjust = 0, vjust = 0
to specify
the lower left corner, and other values of hjust
and vjust
for any other relative location you want to
specify.
For a full list of ... options, see geom_label
.
# Draw onto a 1*1 drawing surface ggdraw() + draw_text("Hello World!", x = 0.5, y = 0.5) # # Adorn a plot from the Anscombe data set of "identical" data. library(ggplot2) p <- ggplot(anscombe, aes(x1, y1)) + geom_point() + geom_smooth() three_strings <- c("Hello World!", "to be or not to be", "over and out") p + draw_text(three_strings, x = 8:10, y = 5:7, hjust = 0)
# Draw onto a 1*1 drawing surface ggdraw() + draw_text("Hello World!", x = 0.5, y = 0.5) # # Adorn a plot from the Anscombe data set of "identical" data. library(ggplot2) p <- ggplot(anscombe, aes(x1, y1)) + geom_point() + geom_smooth() three_strings <- c("Hello World!", "to be or not to be", "over and out") p + draw_text(three_strings, x = 8:10, y = 5:7, hjust = 0)
This function extracts just the legend from a ggplot
get_legend(plot)
get_legend(plot)
plot |
A ggplot or gtable from which to retrieve the legend |
A gtable object holding just the legend or NULL
if there is no legend.
library(ggplot2) theme_set(theme_half_open()) p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line() plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + geom_point(size=2.5) # Note that these cannot be aligned vertically due to the legend in the plot.mpg ggdraw(plot_grid(p1, plot.mpg, ncol=1, align='v')) legend <- get_legend(plot.mpg) plot.mpg <- plot.mpg + theme(legend.position='none') # Now plots are aligned vertically with the legend to the right ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'), plot_grid(NULL, legend, ncol=1), rel_widths=c(1, 0.2)))
library(ggplot2) theme_set(theme_half_open()) p1 <- ggplot(mtcars, aes(mpg, disp)) + geom_line() plot.mpg <- ggplot(mpg, aes(x = cty, y = hwy, colour = factor(cyl))) + geom_point(size=2.5) # Note that these cannot be aligned vertically due to the legend in the plot.mpg ggdraw(plot_grid(p1, plot.mpg, ncol=1, align='v')) legend <- get_legend(plot.mpg) plot.mpg <- plot.mpg + theme(legend.position='none') # Now plots are aligned vertically with the legend to the right ggdraw(plot_grid(plot_grid(p1, plot.mpg, ncol=1, align='v'), plot_grid(NULL, legend, ncol=1), rel_widths=c(1, 0.2)))
get_panel()
extracts just the main panel from a ggplot or a specified panel
in a faceted plot. get_panel_component()
extracts components from the
panel, such as geoms.
get_panel(plot, panel = NULL, return_all = FALSE) get_panel_component(panel, pattern)
get_panel(plot, panel = NULL, return_all = FALSE) get_panel_component(panel, pattern)
plot |
A ggplot or gtable from which to retrieve the panel |
panel |
An integer indicating which panel to pull. ggplot orders panels column-wise, so this is in order from the top left down. |
return_all |
If there is more than one panel, should all be returned
as a list? Default is |
pattern |
the name of the component |
A gtable object holding the panel(s) or a grob of the component
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() plot_panel <- get_panel(p) ggdraw(plot_panel) ggdraw(get_panel_component(plot_panel, "geom_point"))
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() plot_panel <- get_panel(p) ggdraw(plot_panel) ggdraw(get_panel_component(plot_panel, "geom_point"))
Extract plot components from a ggplot or gtable. get_plot_component()
extracts grobs or a list of grobs. plot_component_names()
provides the
names of the components in the plot. plot_components()
returns all
components as a list.
get_plot_component(plot, pattern, return_all = FALSE) plot_component_names(plot) plot_components(plot)
get_plot_component(plot, pattern, return_all = FALSE) plot_component_names(plot) plot_components(plot)
plot |
A ggplot or gtable to extract from. |
pattern |
The name of the component. |
return_all |
If there is more than one component, should all be returned
as a list? Default is |
A grob or list of grobs (get_plot_component()
, plot_components()
)
or a character vector (plot_component_names()
)
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() ggdraw(get_plot_component(p, "ylab-l"))
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() ggdraw(get_plot_component(p, "ylab-l"))
These functions extract just the titles from a ggplot. get_title()
pulls
the title, while get_subtitle()
pulls the subtitle.
get_title(plot) get_subtitle(plot)
get_title(plot) get_subtitle(plot)
plot |
A ggplot or gtable. |
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() + labs( title = "Plot title", subtitle = "Plot subtitle" ) ggdraw(get_title(p)) ggdraw(get_subtitle(p))
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() + labs( title = "Plot title", subtitle = "Plot subtitle" ) ggdraw(get_title(p)) ggdraw(get_subtitle(p))
These functions extract just the axes from a ggplot. get_y_axis()
pulls
the y-axis, while get_x_axis()
pulls the x-axis.
get_y_axis(plot, position = c("left", "right")) get_x_axis(plot, position = c("bottom", "top"))
get_y_axis(plot, position = c("left", "right")) get_x_axis(plot, position = c("bottom", "top"))
plot |
A ggplot or gtable. |
position |
Which side of the plot is the axis on? For the x-axis, this can be "top" or "bottom", and for the y-axis, it can be "left" or "right". |
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() ggdraw(get_y_axis(p)) p <- p + scale_x_continuous(position = "top") ggdraw(get_x_axis(p, position = "top"))
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() ggdraw(get_y_axis(p)) p <- p + scale_x_continuous(position = "top") ggdraw(get_x_axis(p, position = "top"))
Set up a drawing layer on top of a ggplot.
ggdraw(plot = NULL, xlim = c(0, 1), ylim = c(0, 1), clip = "off")
ggdraw(plot = NULL, xlim = c(0, 1), ylim = c(0, 1), clip = "off")
plot |
The plot to use as a starting point. Can be a ggplot2 plot, an arbitrary
grob or gtable, or a recorded base-R plot, as in |
xlim |
The x-axis limits for the drawing layer. |
ylim |
The y-axis limits for the drawing layer. |
clip |
Should drawing be clipped to the set limits? The default is no ("off"). |
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() + theme_minimal_grid() ggdraw(p) + draw_label("Draft", colour = "#80404080", size = 120, angle = 45)
library(ggplot2) p <- ggplot(mpg, aes(displ, cty)) + geom_point() + theme_minimal_grid() ggdraw(p) + draw_label("Draft", colour = "#80404080", size = 120, angle = 45)
ggsave()
.This function behaves just like ggsave()
from ggplot2. The main difference is
that by default it doesn't use the Dingbats font for pdf output. The Dingbats font
causes problems with some pdf readers.
ggsave2( filename, plot = ggplot2::last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c("in", "cm", "mm"), dpi = 300, limitsize = TRUE, ... )
ggsave2( filename, plot = ggplot2::last_plot(), device = NULL, path = NULL, scale = 1, width = NA, height = NA, units = c("in", "cm", "mm"), dpi = 300, limitsize = TRUE, ... )
filename |
Filename of the plot. |
plot |
Plot to save, defaults to last plot displayed. |
device |
Device to use, automatically extract from file name extension. |
path |
Path to save plot to (if you just want to set |
scale |
Scaling factor. |
width |
Width (defaults to the width of current plotting window). |
height |
Height (defaults to the height of current plotting window). |
units |
Units for width and height when either one is explicitly specified (in, cm, or mm). |
dpi |
DPI to use for raster graphics. |
limitsize |
When |
... |
Other arguments to be handed to the plot device. |
Remove named elements from gtable
gtable_remove_grobs(table, names, ...)
gtable_remove_grobs(table, names, ...)
table |
The table from which grobs should be removed |
names |
A character vector of the grob names (as listed in |
... |
Other parameters passed through to |
Set the width of given columns to 0.
gtable_squash_cols(table, cols)
gtable_squash_cols(table, cols)
table |
The gtable on which to operate |
cols |
Numerical vector indicating the columns whose width should be set to zero. |
Set the height of given rows to 0.
gtable_squash_rows(table, rows)
gtable_squash_rows(table, rows)
table |
The gtable on which to operate |
rows |
Numerical vector indicating the rows whose heights should be set to zero. |
The function insert_xaxis_grob()
inserts a grob at the top or bottom of the plot panel in a ggplot2 plot.
insert_xaxis_grob( plot, grob, height = grid::unit(0.2, "null"), position = c("top", "bottom"), clip = "on" ) insert_yaxis_grob( plot, grob, width = grid::unit(0.2, "null"), position = c("right", "left"), clip = "on" )
insert_xaxis_grob( plot, grob, height = grid::unit(0.2, "null"), position = c("top", "bottom"), clip = "on" ) insert_yaxis_grob( plot, grob, width = grid::unit(0.2, "null"), position = c("right", "left"), clip = "on" )
plot |
The plot into which the grob will be inserted. |
grob |
The grob to insert. This will generally have been obtained via |
height |
The height of the grob, in grid units. Used by |
position |
The position of the grob. Can be |
clip |
Set to "off" to turn off clipping of the inserted grob. |
width |
The width of the grob, in grid units. Used by |
For usage examples, see axis_canvas()
.
This function provides a simple way to modify the panel border in ggplot2. It
doesn't do anything that can't be done just the same with theme()
. However, it
saves some typing.
panel_border(color = "grey85", size = 1, linetype = 1, remove = FALSE, colour)
panel_border(color = "grey85", size = 1, linetype = 1, remove = FALSE, colour)
color , colour
|
The color of the border. |
size |
Size. Needs to be twice as large as desired outcome when panel clipping is on (the default). |
linetype |
Line type. |
remove |
If |
Arrange multiple plots into a grid.
plot_grid( ..., plotlist = NULL, align = c("none", "h", "v", "hv"), axis = c("none", "l", "r", "t", "b", "lr", "tb", "tblr"), nrow = NULL, ncol = NULL, rel_widths = 1, rel_heights = 1, labels = NULL, label_size = 14, label_fontfamily = NULL, label_fontface = "bold", label_colour = NULL, label_x = 0, label_y = 1, hjust = -0.5, vjust = 1.5, scale = 1, greedy = TRUE, byrow = TRUE, cols = NULL, rows = NULL )
plot_grid( ..., plotlist = NULL, align = c("none", "h", "v", "hv"), axis = c("none", "l", "r", "t", "b", "lr", "tb", "tblr"), nrow = NULL, ncol = NULL, rel_widths = 1, rel_heights = 1, labels = NULL, label_size = 14, label_fontfamily = NULL, label_fontface = "bold", label_colour = NULL, label_x = 0, label_y = 1, hjust = -0.5, vjust = 1.5, scale = 1, greedy = TRUE, byrow = TRUE, cols = NULL, rows = NULL )
... |
List of plots to be arranged into the grid. The plots can be any objects that
the function |
plotlist |
(optional) List of plots to display. Alternatively, the plots can be provided individually as the first n arguments of the function plot_grid (see examples). |
align |
(optional) Specifies whether graphs in the grid should be horizontally ("h") or vertically ("v") aligned. Options are "none" (default), "hv" (align in both directions), "h", and "v". |
axis |
(optional) Specifies whether graphs should be aligned by the left ("l"), right ("r"), top ("t"), or bottom ("b")
margins. Options are "none" (default), or a string of any combination of l, r, t, and b in any order (e.g. "tblr" or "rlbt" for aligning all margins).
Must be specified if any of the graphs are complex (e.g. faceted) and alignment is specified and desired. See |
nrow |
(optional) Number of rows in the plot grid. |
ncol |
(optional) Number of columns in the plot grid. |
rel_widths |
(optional) Numerical vector of relative columns widths. For example, in a two-column
grid, |
rel_heights |
(optional) Numerical vector of relative rows heights. Works just as
|
labels |
(optional) List of labels to be added to the plots. You can also set |
label_size |
(optional) Numerical value indicating the label size. Default is 14. |
label_fontfamily |
(optional) Font family of the plot labels. If not provided, is taken from the current theme. |
label_fontface |
(optional) Font face of the plot labels. Default is "bold". |
label_colour |
(optional) Color of the plot labels. If not provided, is taken from the current theme. |
label_x |
(optional) Single value or vector of x positions for plot labels, relative to each subplot. Defaults to 0 for all labels. (Each label is placed all the way to the left of each plot.) |
label_y |
(optional) Single value or vector of y positions for plot labels, relative to each subplot. Defaults to 1 for all labels. (Each label is placed all the way to the top of each plot.) |
hjust |
Adjusts the horizontal position of each label. More negative values move the label further to the right on the plot canvas. Can be a single value (applied to all labels) or a vector of values (one for each label). Default is -0.5. |
vjust |
Adjusts the vertical position of each label. More positive values move the label further down on the plot canvas. Can be a single value (applied to all labels) or a vector of values (one for each label). Default is 1.5. |
scale |
Individual number or vector of numbers greater than 0. Enables you to scale the size of all or
select plots. Usually it's preferable to set margins instead of using |
greedy |
(optional) How should margins be adjusted during alignment. See |
byrow |
Logical value indicating if the plots should be arrange by row (default) or by column. |
cols |
Deprecated. Use |
rows |
Deprecated. Use |
library(ggplot2) df <- data.frame( x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4 ) p1 <- ggplot(df, aes(x, y1)) + geom_point() p2 <- ggplot(df, aes(x, y2)) + geom_point() p3 <- ggplot(df, aes(x, y3)) + geom_point() p4 <- ggplot(df, aes(x, y4)) + geom_point() p5 <- ggplot(mpg, aes(as.factor(year), hwy)) + geom_boxplot() + facet_wrap(~class, scales = "free_y") # simple grid plot_grid(p1, p2, p3, p4) # simple grid with labels and aligned plots plot_grid( p1, p2, p3, p4, labels = c('A', 'B', 'C', 'D'), align="hv" ) # manually setting the number of rows, auto-generate upper-case labels plot_grid(p1, p2, p3, nrow = 3, labels = "AUTO", label_size = 12, align = "v" ) # making rows and columns of different widths/heights plot_grid( p1, p2, p3, p4, align = 'hv', rel_heights = c(2,1), rel_widths = c(1,2) ) # aligning complex plots in a grid plot_grid( p1, p5, align = "h", axis = "b", nrow = 1, rel_widths = c(1, 2) ) # more examples #' # missing plots in some grid locations, auto-generate lower-case labels plot_grid( p1, NULL, NULL, p2, p3, NULL, ncol = 2, labels = "auto", label_size = 12, align = "v" ) # can arrange plots on the grid by column as well as by row. plot_grid( p1, NULL, p2, NULL, p3, ncol = 2, byrow = TRUE ) # can align top of plotting area as well as bottom plot_grid( p1, p5, align = "h", axis = "tb", nrow = 1, rel_widths = c(1, 2) ) # other types of plots not generated with ggplot p6 <- ~{ par( mar = c(3, 3, 1, 1), mgp = c(2, 1, 0) ) plot(sqrt) } p7 <- function() { par( mar = c(2, 2, 1, 1), mgp = c(2, 1, 0) ) image(volcano) } p8 <- grid::circleGrob() plot_grid(p1, p6, p7, p8, labels = "AUTO", scale = c(1, .9, .9, .7))
library(ggplot2) df <- data.frame( x = 1:10, y1 = 1:10, y2 = (1:10)^2, y3 = (1:10)^3, y4 = (1:10)^4 ) p1 <- ggplot(df, aes(x, y1)) + geom_point() p2 <- ggplot(df, aes(x, y2)) + geom_point() p3 <- ggplot(df, aes(x, y3)) + geom_point() p4 <- ggplot(df, aes(x, y4)) + geom_point() p5 <- ggplot(mpg, aes(as.factor(year), hwy)) + geom_boxplot() + facet_wrap(~class, scales = "free_y") # simple grid plot_grid(p1, p2, p3, p4) # simple grid with labels and aligned plots plot_grid( p1, p2, p3, p4, labels = c('A', 'B', 'C', 'D'), align="hv" ) # manually setting the number of rows, auto-generate upper-case labels plot_grid(p1, p2, p3, nrow = 3, labels = "AUTO", label_size = 12, align = "v" ) # making rows and columns of different widths/heights plot_grid( p1, p2, p3, p4, align = 'hv', rel_heights = c(2,1), rel_widths = c(1,2) ) # aligning complex plots in a grid plot_grid( p1, p5, align = "h", axis = "b", nrow = 1, rel_widths = c(1, 2) ) # more examples #' # missing plots in some grid locations, auto-generate lower-case labels plot_grid( p1, NULL, NULL, p2, p3, NULL, ncol = 2, labels = "auto", label_size = 12, align = "v" ) # can arrange plots on the grid by column as well as by row. plot_grid( p1, NULL, p2, NULL, p3, ncol = 2, byrow = TRUE ) # can align top of plotting area as well as bottom plot_grid( p1, p5, align = "h", axis = "tb", nrow = 1, rel_widths = c(1, 2) ) # other types of plots not generated with ggplot p6 <- ~{ par( mar = c(3, 3, 1, 1), mgp = c(2, 1, 0) ) plot(sqrt) } p7 <- function() { par( mar = c(2, 2, 1, 1), mgp = c(2, 1, 0) ) image(volcano) } p8 <- grid::circleGrob() plot_grid(p1, p6, p7, p8, labels = "AUTO", scale = c(1, .9, .9, .7))
Null devices to be used when rendering graphics in the background. See
set_null_device()
for details.
png_null_device(width, height) pdf_null_device(width, height) cairo_null_device(width, height) agg_null_device(width, height)
png_null_device(width, height) pdf_null_device(width, height) cairo_null_device(width, height) agg_null_device(width, height)
width |
Device width in inch |
height |
Device height in inch |
These functions create customizable legend key glyphs, such as filled rectangles or circles.
rectangle_key_glyph( colour = NA, fill = fill, alpha = alpha, size = size, linetype = linetype, padding = unit(c(0, 0, 0, 0), "pt"), color ) circle_key_glyph( colour = NA, fill = fill, alpha = alpha, size = size, linetype = linetype, padding = unit(c(0, 0, 0, 0), "pt"), color )
rectangle_key_glyph( colour = NA, fill = fill, alpha = alpha, size = size, linetype = linetype, padding = unit(c(0, 0, 0, 0), "pt"), color ) circle_key_glyph( colour = NA, fill = fill, alpha = alpha, size = size, linetype = linetype, padding = unit(c(0, 0, 0, 0), "pt"), color )
colour , color
|
Unquoted name of the aesthetic to use for the outline color,
usually |
fill |
Unquoted name of the aesthetic to use for the fill color,
usually |
alpha |
Unquoted name of the aesthetic to use for alpha,
usually |
size |
Unquoted name of the aesthetic to use for the line thickness of the
outline, usually |
linetype |
Unquoted name of the aesthetic to use for the line type of the
outline, usually |
padding |
Unit vector with four elements specifying the top, right, bottom, and left padding from the edges of the legend key to the edges of the key glyph. |
library(ggplot2) set.seed(1233) df <- data.frame( x = sample(letters[1:2], 10, TRUE), y = rnorm(10) ) ggplot(df, aes(x, y, color = x)) + geom_boxplot( key_glyph = rectangle_key_glyph(fill = color, padding = margin(3, 3, 3, 3)) ) ggplot(df, aes(x, y, color = x)) + geom_boxplot( key_glyph = circle_key_glyph( fill = color, color = "black", linetype = 3, size = 0.3, padding = margin(2, 2, 2, 2) ) )
library(ggplot2) set.seed(1233) df <- data.frame( x = sample(letters[1:2], 10, TRUE), y = rnorm(10) ) ggplot(df, aes(x, y, color = x)) + geom_boxplot( key_glyph = rectangle_key_glyph(fill = color, padding = margin(3, 3, 3, 3)) ) ggplot(df, aes(x, y, color = x)) + geom_boxplot( key_glyph = circle_key_glyph( fill = color, color = "black", linetype = 3, size = 0.3, padding = margin(2, 2, 2, 2) ) )
ggsave()
, with better support for multi-figure plots.This function replaces the standard ggsave()
function for saving a plot into a file. It
has several advantages over ggsave()
. First, it uses default sizes that work well with
the cowplot theme, so that frequently a plot size does not have to be explicitly specified. Second, it
acknowledges that one often first develops individual plots and then combines them into
multi-plot figures, and it makes it easy—in combination with plot_grid()
—to carry out
this workflow. Finally, it makes it easy to adjust the aspect ratio of the figure, which is
frequently necessary to accommodate plots with or without figure legend.
save_plot( filename, plot, ncol = 1, nrow = 1, base_height = 3.71, base_asp = 1.618, base_width = NULL, ..., cols, rows, base_aspect_ratio, width, height )
save_plot( filename, plot, ncol = 1, nrow = 1, base_height = 3.71, base_asp = 1.618, base_width = NULL, ..., cols, rows, base_aspect_ratio, width, height )
filename |
Name of the plot file to generate. |
plot |
Plot to save. |
ncol |
Number of subplot columns. |
nrow |
Number of subplot rows. |
base_height |
The height (in inches) of the plot or of one sub-plot if |
base_asp |
The aspect ratio (width/height) of the plot or of one sub-plot if |
base_width |
The width (in inches) of the plot or of one sub-plot if |
... |
Other arguments to be handed to |
cols |
Deprecated. Use |
rows |
Deprecated. Use |
base_aspect_ratio |
Deprecated. Use |
width |
Deprecated. Don't use. |
height |
Deprecated. Don't use. |
The key idea for this function is that plots are often grids, with sup-plots at the individual grid locations. Therefore, for this function we specify a base width and aspect ratio that apply to one sup-plot, and we then specify how many rows and columns of subplots we have. This means that if we have code that can save a single figure, it is trivial to adapt this code to save a combination of multiple comparable figures. See examples for details.
library(ggplot2) # save a single plot with a legend p1 <- ggplot(mpg, aes(x = cty, y = hwy, color = factor(cyl))) + geom_point(size = 2) + theme_half_open() file1 <- tempfile("file1", fileext = ".png") file2 <- tempfile("file2", fileext = ".png") save_plot(file1, p1) # same as file1 but determine base_width given base_height save_plot(file2, p1, base_height = NULL, base_width = 6) # save a single plot without legend, adjust aspect ratio x <- (1:100)/10 p3 <- ggplot(data.frame(x = x, y = x*sin(x)), aes(x, y)) + geom_line() + theme_minimal_hgrid() file3 <- tempfile("file3", fileext = ".pdf") save_plot(file3, p3, base_asp = 1.1) # now combine with a second plot and save p3b <- ggplot(data.frame(x = x, y = cos(x)+x), aes(x, y)) + geom_line() + theme_minimal_hgrid() p4 <- plot_grid(p3, p3b, labels = "AUTO") file4 <- tempfile("file4", fileext = ".pdf") save_plot(file4, p4, ncol = 2, base_asp = 1.1)
library(ggplot2) # save a single plot with a legend p1 <- ggplot(mpg, aes(x = cty, y = hwy, color = factor(cyl))) + geom_point(size = 2) + theme_half_open() file1 <- tempfile("file1", fileext = ".png") file2 <- tempfile("file2", fileext = ".png") save_plot(file1, p1) # same as file1 but determine base_width given base_height save_plot(file2, p1, base_height = NULL, base_width = 6) # save a single plot without legend, adjust aspect ratio x <- (1:100)/10 p3 <- ggplot(data.frame(x = x, y = x*sin(x)), aes(x, y)) + geom_line() + theme_minimal_hgrid() file3 <- tempfile("file3", fileext = ".pdf") save_plot(file3, p3, base_asp = 1.1) # now combine with a second plot and save p3b <- ggplot(data.frame(x = x, y = cos(x)+x), aes(x, y)) + geom_line() + theme_minimal_hgrid() p4 <- plot_grid(p3, p3b, labels = "AUTO") file4 <- tempfile("file4", fileext = ".pdf") save_plot(file4, p4, ncol = 2, base_asp = 1.1)
The function as_grob()
needs to open a graphics device to render ggplot objects into
grid graphics objects. Unfortunately, there is no universally reliable graphics device available
in R that always works. Therefore, this function allows you to switch out the null device.
set_null_device(null_device)
set_null_device(null_device)
null_device |
Either a string that defines the null device ("pdf", "png", "cairo", "agg") or a function that returns a new graphics device. |
You need to be aware that some graphics devices cause side effects when used as null devices.
If you use an interactive device as null device, you may see an empty plot window pop up. Similarly,
if you use a graphics device that writes a file, then you may find temporary files associated
with the device. The default null device, pdf(NULL)
, does not cause these side effects. However, it has
has other limitations. For example, on OS X, it cannot use all the fonts that are available on the
system. The ragg device can use all fonts, but it will create temporary files.
Available null devices are: pdf_null_device()
, png_null_device()
,
cairo_null_device()
, agg_null_device()
set_null_device("png") # set the png null device # create a jpeg null device jpeg_null_device <- function(width, height) { jpeg( filename = tempfile(pattern = "jpeg_null_plot", fileext = ".jpg"), width = width, height = height, units = "in", res = 96 ) dev.control("enable") } set_null_device(jpeg_null_device)
set_null_device("png") # set the png null device # create a jpeg null device jpeg_null_device <- function(width, height) { jpeg( filename = tempfile(pattern = "jpeg_null_plot", fileext = ".jpg"), width = width, height = height, units = "in", res = 96 ) dev.control("enable") } set_null_device(jpeg_null_device)
Stamp plots with a label, such as good, bad, or ugly.
stamp( p, label, color = "black", alpha = 1, vjust = 1.1, hjust = 1, size = 14, family = "", fontface = "bold", clip = "on", colour ) stamp_good(p, ...) stamp_bad(p, ...) stamp_wrong(p, ...) stamp_ugly(p, ...)
stamp( p, label, color = "black", alpha = 1, vjust = 1.1, hjust = 1, size = 14, family = "", fontface = "bold", clip = "on", colour ) stamp_good(p, ...) stamp_bad(p, ...) stamp_wrong(p, ...) stamp_ugly(p, ...)
p |
The plot to stamp |
label |
The text label used for the stamp |
color , colour
|
The color of the stamp |
alpha |
Transparency level of the stamp |
hjust , vjust
|
Horizontal and vertical adjustment of the label |
size |
Font size |
family |
Font family |
fontface |
Font face |
clip |
Should figure be clipped (default is "on") |
... |
Arguments handed off to |
library(ggplot2) p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color = factor(Petal.Width))) stamp_bad(p + guides(color = "none")) stamp_ugly(p)
library(ggplot2) p <- ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width)) + geom_point(aes(color = factor(Petal.Width))) stamp_bad(p + guides(color = "none")) stamp_ugly(p)
The default cowplot theme, with a simple half-open frame and no grid. This theme used to be set by default after loading the cowplot package, but this is no longer the case.
theme_cowplot( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14 ) theme_half_open( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14 )
theme_cowplot( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14 ) theme_half_open( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14 )
font_size |
Overall font size. |
font_family |
Font family for plot title, axis titles and labels, legend texts, etc. |
line_size |
Line size for axis lines. |
rel_small |
Relative size of small text (e.g., axis tick labels) |
rel_tiny |
Relative size of tiny text (e.g., caption) |
rel_large |
Relative size of large text (e.g., title) |
Both theme_cowplot()
and theme_half_open()
provide exactly the same styling.
The theme.
library(ggplot2) ggplot(mtcars, aes(disp, mpg)) + geom_point() + theme_cowplot(font_size = 12)
library(ggplot2) ggplot(mtcars, aes(disp, mpg)) + geom_point() + theme_cowplot(font_size = 12)
The theme created by this function is useful for plotting maps with cowplot default sizing.
theme_map( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14 )
theme_map( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14 )
font_size |
Overall font size. Default is 14. |
font_family |
Base font family. |
line_size |
Line size for axis lines. |
rel_small |
Relative size of small text (e.g., axis tick labels) |
rel_tiny |
Relative size of tiny text (e.g., caption) |
rel_large |
Relative size of large text (e.g., title) |
The theme.
library(ggplot2) library(maps) usa_data = map_data("usa") ggplot(usa_data, aes(long, lat, fill = region)) + geom_polygon() + theme_map() ggplot(usa_data, aes(long, lat, fill = region)) + facet_wrap(~region, scales = "free") + geom_polygon() + theme_map()
library(ggplot2) library(maps) usa_data = map_data("usa") ggplot(usa_data, aes(long, lat, fill = region)) + geom_polygon() + theme_map() ggplot(usa_data, aes(long, lat, fill = region)) + facet_wrap(~region, scales = "free") + geom_polygon() + theme_map()
Three minimalistic themes that provide either a full grid,
a horizontal grid, or a vertical grid. Similar to theme_minimal()
, but with some
stylistic differences. Most importantly, these themes do not draw minor grid lines.
Also, font sizes are coordinated with theme_half_open()
and with the defaults
in the save_plot()
function.
theme_minimal_grid( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14, color = "grey85", colour ) theme_minimal_vgrid( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14, color = "grey85", colour ) theme_minimal_hgrid( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14, color = "grey85", colour )
theme_minimal_grid( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14, color = "grey85", colour ) theme_minimal_vgrid( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14, color = "grey85", colour ) theme_minimal_hgrid( font_size = 14, font_family = "", line_size = 0.5, rel_small = 12/14, rel_tiny = 11/14, rel_large = 16/14, color = "grey85", colour )
font_size |
Overall font size. |
font_family |
Font family for plot title, axis titles and labels, legend texts, etc. |
line_size |
Line size for grid lines. |
rel_small |
Relative size of small text (e.g., axis tick labels) |
rel_tiny |
Relative size of tiny text (e.g., caption) |
rel_large |
Relative size of large text (e.g., title) |
color , colour
|
Color of grid lines. |
theme_minimal_grid()
provides a minimal grid theme. theme_minimal_hgrid()
strips down
this theme even further and draws only horizontal lines, and theme_minimal_vgrid()
does the same for vertical lines.
library(ggplot2) # theme_minimal_grid() ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point() + theme_minimal_grid() # theme_minimal_hgrid() ggplot(mtcars, aes(x = carb)) + geom_bar(fill = "lightblue") + scale_y_continuous(limits = c(0, 11.5), expand = c(0, 0)) + theme_minimal_hgrid() # theme_minimal_vgrid() ggplot(mtcars, aes(x = carb)) + geom_bar(fill = "lightblue") + scale_y_continuous(limits = c(0, 11.5), expand = c(0, 0)) + coord_flip() + theme_minimal_vgrid()
library(ggplot2) # theme_minimal_grid() ggplot(iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point() + theme_minimal_grid() # theme_minimal_hgrid() ggplot(mtcars, aes(x = carb)) + geom_bar(fill = "lightblue") + scale_y_continuous(limits = c(0, 11.5), expand = c(0, 0)) + theme_minimal_hgrid() # theme_minimal_vgrid() ggplot(mtcars, aes(x = carb)) + geom_bar(fill = "lightblue") + scale_y_continuous(limits = c(0, 11.5), expand = c(0, 0)) + coord_flip() + theme_minimal_vgrid()
The theme created by this function shows nothing but the plot panel.
theme_nothing(font_size = 14, font_family = "", rel_small = 12/14)
theme_nothing(font_size = 14, font_family = "", rel_small = 12/14)
font_size |
Overall font size. Default is 14. |
font_family |
Base font family. |
rel_small |
Relative size of small text |
The theme.
library(ggplot2) ggplot(mtcars, aes(disp, mpg, color = cyl)) + geom_point() + theme_nothing()
library(ggplot2) ggplot(mtcars, aes(disp, mpg, color = cyl)) + geom_point() + theme_nothing()