Title: | Hacks for 'ggplot2' |
---|---|
Description: | A 'ggplot2' extension that does a variety of little helpful things. The package extends 'ggplot2' facets through customisation, by setting individual scales per panel, resizing panels and providing nested facets. Also allows multiple colour and fill scales per plot. Also hosts a smaller collection of stats, geoms and axis guides. |
Authors: | Teun van den Brand [aut, cre] |
Maintainer: | Teun van den Brand <[email protected]> |
License: | MIT + file LICENSE |
Version: | 0.2.8.9000 |
Built: | 2024-11-16 11:25:20 UTC |
Source: | https://github.com/teunbrand/ggh4x |
This function limits the panels in which a layer is displayed. It can be used to make panel-specific annotations.
at_panel(layer, expr)
at_panel(layer, expr)
layer |
A |
expr |
An |
The expr
argument's expression will be evaluated in the context of the
plot's layout. This is an internal data.frame
structure that isn't
ordinarily exposed to users, so it will require some extra knowledge. For
most facets, the layout describes the panels with one panel per row. It
typically has COL
, ROW
and PANEL
columns that keep track of where a
panel goes in a grid-layout of cells. In addition, the layout contains the
facetting variables provided to the facets
or rows
and cols
arguments
of the facets. For example, if we have a plot facetted on the var
variable
with the levels A
, B
and C
, as 1 row and 3 columns, we might target
the second B
panel iwth any of these expressions: var == "B"
,
PANEL == 2
or COL == 2
. We can inspect the layout structure by using
ggplot_build(p)$layout$layout
, wherein p
is a plot.
A modified layer
which will only show in some panels.
p <- ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(year ~ drv) anno <- annotate("text", x = 3, y = 40, label = "My text") # Target specific panels p + at_panel(anno, PANEL %in% c(2, 4)) # Target a variable p + at_panel(anno, drv == "f") # Or combine variable with position p + at_panel(anno, drv == "f" & ROW == 2)
p <- ggplot(mpg, aes(displ, hwy)) + geom_point() + facet_grid(year ~ drv) anno <- annotate("text", x = 3, y = 40, label = "My text") # Target specific panels p + at_panel(anno, PANEL %in% c(2, 4)) # Target a variable p + at_panel(anno, drv == "f") # Or combine variable with position p + at_panel(anno, drv == "f" & ROW == 2)
This a function factory that allows the centering of scales around a certain value while still including all values. Convenient for centering log2 fold change limits around zero.
center_limits(around = 0)
center_limits(around = 0)
around |
A |
A function
that takes limits and returns expanded limits
centered at the around
argument.
center_limits(5)(c(3,8)) g <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = log2(Petal.Width / Petal.Length))) + geom_point() + scale_colour_gradient2(limits = center_limits())
center_limits(5)(c(3,8)) g <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = log2(Petal.Width / Petal.Length))) + geom_point() + scale_colour_gradient2(limits = center_limits())
This coordinate system places the plot axes at interior positions. Other
than this, it behaves like coord_cartesian()
or
coord_fixed()
(the latter if the ratio
argument
is set).
coord_axes_inside( xlim = NULL, ylim = NULL, xintercept = 0, yintercept = 0, labels_inside = FALSE, ratio = NULL, expand = TRUE, default = FALSE, clip = "on" )
coord_axes_inside( xlim = NULL, ylim = NULL, xintercept = 0, yintercept = 0, labels_inside = FALSE, ratio = NULL, expand = TRUE, default = FALSE, clip = "on" )
xlim , ylim
|
Limits for the x and y axes. |
xintercept , yintercept
|
A |
labels_inside |
One of |
ratio |
Either |
expand |
If |
default |
Is this the default coordinate system? If |
clip |
Should drawing be clipped to the extent of the plot panel? A
setting of |
A CoordAxesInside
object, which can be added to a plot.
# A standard plot p <- ggplot(mpg, aes(scale(displ), scale(hwy))) + geom_point() + theme(axis.line = element_line()) # By default, axis text is still placed outside the panel p + coord_axes_inside() # However, this can simply be changed p + coord_axes_inside(labels_inside = TRUE) # The place where the axes meet can be changed p + coord_axes_inside(xintercept = 1, yintercept = -1) # Axes snap to the nearest limit when out-of-bounds p + coord_axes_inside(xintercept = -5, yintercept = Inf, clip = "off") # Can be combined with other non-default axes p + guides(x = "axis_minor") + coord_axes_inside()
# A standard plot p <- ggplot(mpg, aes(scale(displ), scale(hwy))) + geom_point() + theme(axis.line = element_line()) # By default, axis text is still placed outside the panel p + coord_axes_inside() # However, this can simply be changed p + coord_axes_inside(labels_inside = TRUE) # The place where the axes meet can be changed p + coord_axes_inside(xintercept = 1, yintercept = -1) # Axes snap to the nearest limit when out-of-bounds p + coord_axes_inside(xintercept = -5, yintercept = Inf, clip = "off") # Can be combined with other non-default axes p + guides(x = "axis_minor") + coord_axes_inside()
These functions take a vector of arguments and pass on the
ith item of the vector to an
ith call of a function. The
elem_list_text
and elem_list_rect
are convenience functions for
constructing lists of element_text()
and
element_rect()
theme elements.
distribute_args(..., .fun = element_text, .cull = TRUE) elem_list_text(...) elem_list_rect(...)
distribute_args(..., .fun = element_text, .cull = TRUE) elem_list_text(...) elem_list_rect(...)
... |
Vectorised arguments to pass on to functions. |
.fun |
A function to distribute arguments to. |
.cull |
A |
NA
s and NULL
s will be silently dropped. If you want to pass on a
transparent fill
or colour
argument, you should use the more verbose
character "transparent"
instead. However, you can use a NA
to
indicate that it's argument should not be passed to a function in that
position.
A list
of outputs from fun
.
Whereas the distribute_args
function might seem amenable for
off-label uses elsewhere (besides constructing lists of theme elements), it
is not intended as such. For example, because valid arguments will be
deduced from the formals of a function, using certain functions can be
troublesome. For example, the distribute_args
function does not properly
recognise the utility of a ...
argument in a function that it is supposed
to distribute arguments to. This can be a problem for object-oriented
functions: if the methods contain more arguments than the generic itself,
these extra arguments will be silently dropped.
The element_text()
and
element_rect()
theme elements for a
description of their arguments.
# Providing arguments for `element_rect()` elem_list_rect( # The first element_rect will have linetype 1, the second gets 3 linetype = c(1, 3), # If an argument doesn't exist, it will be silently dropped nonsense_argument = c("I", "will", "be", "filtered", "out") ) # Providing arguments for `element_text()` elem_list_text( # `NA`s will be skipped family = c("mono", NA, "sans"), # Providing a list of more complex arguments. `NULL` will be skipped too. margin = list(NULL, margin(t = 5)) ) # Providing arguments to other functions distribute_args( lineend = c("round", "butt", "square"), # If you want to pass a vector instead of a scalar, you can use a list colour = list(c("blue", "red"), "green"), .fun = element_line )
# Providing arguments for `element_rect()` elem_list_rect( # The first element_rect will have linetype 1, the second gets 3 linetype = c(1, 3), # If an argument doesn't exist, it will be silently dropped nonsense_argument = c("I", "will", "be", "filtered", "out") ) # Providing arguments for `element_text()` elem_list_text( # `NA`s will be skipped family = c("mono", NA, "sans"), # Providing a list of more complex arguments. `NULL` will be skipped too. margin = list(NULL, margin(t = 5)) ) # Providing arguments to other functions distribute_args( lineend = c("round", "butt", "square"), # If you want to pass a vector instead of a scalar, you can use a list colour = list(c("blue", "red"), "green"), .fun = element_line )
The element_part_rect()
function draws sides of a rectangle as theme
elements. It can substitute element_rect()
theme elements.
element_part_rect( side = "tlbr", fill = NULL, colour = NULL, linewidth = NULL, linetype = NULL, color = NULL, inherit.blank = FALSE )
element_part_rect( side = "tlbr", fill = NULL, colour = NULL, linewidth = NULL, linetype = NULL, color = NULL, inherit.blank = FALSE )
side |
A |
fill |
Fill colour. |
colour , color
|
Line/border colour. Color is an alias for colour. |
linewidth |
Line/border size in mm. |
linetype |
Line type. An integer (0:8), a name (blank, solid, dashed, dotted, dotdash, longdash, twodash), or a string with an even number (up to eight) of hexadecimal digits which give the lengths in consecutive positions in the string. |
inherit.blank |
Should this element inherit the existence of an
|
An S3 object of class element_part_rect
.
ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point() + facet_grid(Species ~.) + theme( strip.background = element_part_rect(side = "tb", colour = "black"), panel.background = element_part_rect(side = "l", colour = "black") )
ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point() + facet_grid(Species ~.) + theme( strip.background = element_part_rect(side = "tb", colour = "black"), panel.background = element_part_rect(side = "l", colour = "black") )
This function behaves like ggplot2::facet_grid with default arguments, but has a few extra options. It can draw partial or full axis guides at inner panels, and position scales can be independent.
facet_grid2( rows = NULL, cols = NULL, scales = "fixed", space = "fixed", axes = "margins", remove_labels = "none", independent = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE, render_empty = TRUE, strip = strip_vanilla() )
facet_grid2( rows = NULL, cols = NULL, scales = "fixed", space = "fixed", axes = "margins", remove_labels = "none", independent = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE, render_empty = TRUE, strip = strip_vanilla() )
rows , cols
|
A set of variables or expressions quoted by
For compatibility with the classic interface, |
scales |
A
|
space |
A
|
axes |
A
|
remove_labels |
A
|
independent |
A
|
shrink |
If |
labeller |
A function that takes one data frame of labels and
returns a list or data frame of character vectors. Each input
column corresponds to one factor. Thus there will be more than
one with |
as.table |
If |
switch |
By default, the labels are displayed on the top and
right of the plot. If |
drop |
If |
margins |
Either a logical value or a character
vector. Margins are additional facets which contain all the data
for each of the possible values of the faceting variables. If
|
render_empty |
A |
strip |
An object created by a call to a strip function, such as
|
Both the independent
and space
arguments only have an effect
when the scales
argument in a dimension is free. However, the
independent
and space
arguments can not be used to simultaneously set
an independent scale and have the panel size be proportional to that scale.
A Facet
ggproto object that can be added to a plot.
Other facetting functions:
facet_manual()
,
facet_nested()
,
facet_nested_wrap()
,
facet_wrap2()
p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Repeat all axes for every facet p + facet_grid2(cyl ~ drv, axes = "all") # Repeat only y-axes p + facet_grid2(cyl ~ drv, axes = "y") # Repeat axes without x-labels p + facet_grid2(cyl ~ drv, axes = "all", remove_labels = "x") # Grid facets with independent axes for every panel p + facet_grid2(cyl ~ drv, scales = "free", independent = "all")
p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Repeat all axes for every facet p + facet_grid2(cyl ~ drv, axes = "all") # Repeat only y-axes p + facet_grid2(cyl ~ drv, axes = "y") # Repeat axes without x-labels p + facet_grid2(cyl ~ drv, axes = "all", remove_labels = "x") # Grid facets with independent axes for every panel p + facet_grid2(cyl ~ drv, scales = "free", independent = "all")
In facet_manual()
the layout for panels is determined by a custom design.
Inspired by base-R graphics layout()
function, this
variant of facets offers more freedom in how panels are displayed, but
comes with less guarantees that it looks right.
facet_manual( facets, design = NULL, widths = NULL, heights = NULL, respect = FALSE, drop = TRUE, strip.position = "top", scales = "fixed", axes = "margins", remove_labels = "none", labeller = "label_value", trim_blank = TRUE, strip = strip_vanilla() )
facet_manual( facets, design = NULL, widths = NULL, heights = NULL, respect = FALSE, drop = TRUE, strip.position = "top", scales = "fixed", axes = "margins", remove_labels = "none", labeller = "label_value", trim_blank = TRUE, strip = strip_vanilla() )
facets |
A set of variables or expressions quoted by For compatibility with the classic interface, can also be a
formula or character vector. Use either a one sided formula, |
design |
Specification of panel areas in the layout. Can either be
specified as a |
widths , heights
|
A |
respect |
A |
drop |
If |
strip.position |
By default, the labels are displayed on the top of
the plot. Using |
scales |
A
|
axes |
A
|
remove_labels |
A
|
labeller |
A function that takes one data frame of labels and
returns a list or data frame of character vectors. Each input
column corresponds to one factor. Thus there will be more than
one with |
trim_blank |
A |
strip |
An object created by a call to a strip function, such as
|
A Facet
ggproto object that can be added to a plot.
Other facetting functions:
facet_grid2()
,
facet_nested()
,
facet_nested_wrap()
,
facet_wrap2()
# A standard plot p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() # The `design` argument can be a character string. # New rows are indicated by newline symbol (`\n`), which are added # automatically for multi-line strings. # The `#`-symbol indicates empty cells. design <- " A## AB# #BC ##C " p + facet_manual(~ cyl, design) # Alternatively, the `design` argument can be a matrix. # Using `NA`s will leave the cell empty. design <- matrix(c(1,2,3,3), 2, 2, byrow = TRUE) p + facet_manual(~ cyl, design) # The sizes of columns and rows can be adjusted with the `widths` and # `heights`parameters respectively. p + facet_manual( ~ cyl, t(design), widths = c(2, 1), heights = c(2, 1), respect = TRUE )
# A standard plot p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() # The `design` argument can be a character string. # New rows are indicated by newline symbol (`\n`), which are added # automatically for multi-line strings. # The `#`-symbol indicates empty cells. design <- " A## AB# #BC ##C " p + facet_manual(~ cyl, design) # Alternatively, the `design` argument can be a matrix. # Using `NA`s will leave the cell empty. design <- matrix(c(1,2,3,3), 2, 2, byrow = TRUE) p + facet_manual(~ cyl, design) # The sizes of columns and rows can be adjusted with the `widths` and # `heights`parameters respectively. p + facet_manual( ~ cyl, t(design), widths = c(2, 1), heights = c(2, 1), respect = TRUE )
facet_nested()
forms a matrix of panels defined by row
and column faceting variables and nests grouped facets.
facet_nested( rows = NULL, cols = NULL, scales = "fixed", space = "fixed", axes = "margins", remove_labels = "none", independent = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE, nest_line = element_line(inherit.blank = TRUE), solo_line = FALSE, resect = unit(0, "mm"), render_empty = TRUE, strip = strip_nested(), bleed = NULL )
facet_nested( rows = NULL, cols = NULL, scales = "fixed", space = "fixed", axes = "margins", remove_labels = "none", independent = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, switch = NULL, drop = TRUE, margins = FALSE, nest_line = element_line(inherit.blank = TRUE), solo_line = FALSE, resect = unit(0, "mm"), render_empty = TRUE, strip = strip_nested(), bleed = NULL )
rows , cols
|
A set of variables or expressions quoted by
For compatibility with the classic interface, |
scales |
A
|
space |
A
|
axes |
A
|
remove_labels |
A
|
independent |
A
|
shrink |
If |
labeller |
A function that takes one data frame of labels and
returns a list or data frame of character vectors. Each input
column corresponds to one factor. Thus there will be more than
one with |
as.table |
If |
switch |
By default, the labels are displayed on the top and
right of the plot. If |
drop |
If |
margins |
Either a logical value or a character
vector. Margins are additional facets which contain all the data
for each of the possible values of the faceting variables. If
|
nest_line |
a theme element, either |
solo_line |
A |
resect |
a |
render_empty |
A |
strip |
An object created by a call to a strip function, such as
|
bleed |
the |
This function inherits the capabilities of
facet_grid2()
.
Unlike facet_grid()
, this function only automatically expands
missing variables when they have no variables in that direction, to allow
for unnested variables. It still requires at least one layer to have all
faceting variables.
Hierarchies are inferred from the order of variables supplied to
rows
or cols
. The first variable is interpreted to be the
outermost variable, while the last variable is interpreted to be the
innermost variable. They display order is always such that the outermost
variable is placed the furthest away from the panels. For more information
about the nesting of strips, please visit the documentation of
strip_nested()
.
A FacetNested ggproto object that can be added to a plot.
See strip_nested()
for nested strips. See
ggplot2::facet_grid()
for descriptions of the original
arguments. See grid::unit()
for the construction of a
unit
vector.
Other facetting functions:
facet_grid2()
,
facet_manual()
,
facet_nested_wrap()
,
facet_wrap2()
# A standard plot p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() # Similar to `facet_grid2(..., strip = strip_nested())` p + facet_nested(~ vs + cyl) # The nest line inherits from the global theme p + facet_nested(~ cyl + vs, nest_line = element_line(colour = "red")) + theme(ggh4x.facet.nestline = element_line(linetype = 3))
# A standard plot p <- ggplot(mtcars, aes(mpg, wt)) + geom_point() # Similar to `facet_grid2(..., strip = strip_nested())` p + facet_nested(~ vs + cyl) # The nest line inherits from the global theme p + facet_nested(~ cyl + vs, nest_line = element_line(colour = "red")) + theme(ggh4x.facet.nestline = element_line(linetype = 3))
facet_nested_wrap()
wraps a sequence of panels onto a two-dimensional
layout, and nests grouped facets where possible.
facet_nested_wrap( facets, nrow = NULL, ncol = NULL, scales = "fixed", axes = "margins", remove_labels = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, drop = TRUE, dir = "h", strip.position = "top", nest_line = element_line(inherit.blank = TRUE), solo_line = FALSE, resect = unit(0, "mm"), trim_blank = TRUE, strip = strip_nested(), bleed = NULL )
facet_nested_wrap( facets, nrow = NULL, ncol = NULL, scales = "fixed", axes = "margins", remove_labels = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, drop = TRUE, dir = "h", strip.position = "top", nest_line = element_line(inherit.blank = TRUE), solo_line = FALSE, resect = unit(0, "mm"), trim_blank = TRUE, strip = strip_nested(), bleed = NULL )
facets |
A set of variables or expressions quoted by For compatibility with the classic interface, can also be a
formula or character vector. Use either a one sided formula, |
nrow , ncol
|
Number of rows and columns. |
scales |
A
|
axes |
A
|
remove_labels |
A
|
shrink |
If |
labeller |
A function that takes one data frame of labels and
returns a list or data frame of character vectors. Each input
column corresponds to one factor. Thus there will be more than
one with |
as.table |
If |
drop |
If |
dir |
Direction: either |
strip.position |
By default, the labels are displayed on the top of
the plot. Using |
nest_line |
a theme element, either |
solo_line |
A |
resect |
a |
trim_blank |
A |
strip |
An object created by a call to a strip function, such as
|
bleed |
the |
This function inherits the capabilities of
facet_wrap2()
.
This function only merges strips in the same row or column as they appear
through regular facet_wrap()
layout behaviour.
Hierarchies are inferred from the order of variables supplied to
facets
. The first variable is interpreted to be the outermost
variable, while the last variable is interpreted to be the innermost
variable. They display order is always such that the outermost
variable is placed the furthest away from the panels. For more information
about the nesting of strips, please visit the documentation of
strip_nested()
.
A FacetNestedWrap
ggproto object that can be added to a plot.
See strip_nested()
for nested strips. See
ggplot2::facet_wrap()
for descriptions of the original
arguments. See grid::unit()
for the construction of a
unit
vector.
Other facetting functions:
facet_grid2()
,
facet_manual()
,
facet_nested()
,
facet_wrap2()
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Similar to `facet_wrap2(..., strip = strip_nested())`. p + facet_nested_wrap(vars(cyl, drv)) # A nest line inherits from the global theme p + facet_nested_wrap(vars(cyl, drv), nest_line = element_line(colour = "red")) + theme(ggh4x.facet.nestline = element_line(linetype = 3))
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Similar to `facet_wrap2(..., strip = strip_nested())`. p + facet_nested_wrap(vars(cyl, drv)) # A nest line inherits from the global theme p + facet_nested_wrap(vars(cyl, drv), nest_line = element_line(colour = "red")) + theme(ggh4x.facet.nestline = element_line(linetype = 3))
This function behaves like ggplot2::facet_wrap()
, but has a few
extra options on axis drawing when scales are fixed.
facet_wrap2( facets, nrow = NULL, ncol = NULL, scales = "fixed", axes = "margins", remove_labels = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, drop = TRUE, dir = "h", strip.position = "top", trim_blank = TRUE, strip = strip_vanilla() )
facet_wrap2( facets, nrow = NULL, ncol = NULL, scales = "fixed", axes = "margins", remove_labels = "none", shrink = TRUE, labeller = "label_value", as.table = TRUE, drop = TRUE, dir = "h", strip.position = "top", trim_blank = TRUE, strip = strip_vanilla() )
facets |
A set of variables or expressions quoted by For compatibility with the classic interface, can also be a
formula or character vector. Use either a one sided formula, |
nrow , ncol
|
Number of rows and columns. |
scales |
A
|
axes |
A
|
remove_labels |
A
|
shrink |
If |
labeller |
A function that takes one data frame of labels and
returns a list or data frame of character vectors. Each input
column corresponds to one factor. Thus there will be more than
one with |
as.table |
If |
drop |
If |
dir |
Direction: either |
strip.position |
By default, the labels are displayed on the top of
the plot. Using |
trim_blank |
A |
strip |
An object created by a call to a strip function, such as
|
A Facet
ggproto object that can be added to a plot.
Other facetting functions:
facet_grid2()
,
facet_manual()
,
facet_nested()
,
facet_nested_wrap()
p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Repeat all axes for every facet p + facet_wrap2(vars(class), axes = "all") # Repeat only y-axes p + facet_wrap2(vars(class), axes = "y") # Repeat axes without labels p + facet_wrap2(vars(class), axes = "all", remove_labels = "all") # Repeat axes without x-axis labels p + facet_wrap2(vars(class), axes = "all", remove_labels = "x")
p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Repeat all axes for every facet p + facet_wrap2(vars(class), axes = "all") # Repeat only y-axes p + facet_wrap2(vars(class), axes = "y") # Repeat axes without labels p + facet_wrap2(vars(class), axes = "all", remove_labels = "all") # Repeat axes without x-axis labels p + facet_wrap2(vars(class), axes = "all", remove_labels = "x")
This function allows the tweaking of the position scales (x and y) of individual facets. You can use it to fine-tune limits, breaks and other scale parameters for individual facets, provided the facet allows free scales.
facetted_pos_scales(x = NULL, y = NULL)
facetted_pos_scales(x = NULL, y = NULL)
x , y
|
A |
It is intended that this function works with both
ggplot2::facet_wrap()
and ggplot2::facet_grid()
.
For facet_wrap
, the scales are used for each individual panel. For
facet_grid
, the scales are used for the rows and columns. Note that
these facets must be used with scales = "free"
or "free_x"
or
"free_y"
, depending on what scales are added.
Axis titles are derived from the first scale in the list (or the default
position scale when the first list element is NULL
).
It is allowed to use individual scale
transformations for facets, but this functionality comes with the trade-off
that the out of bounds (oob
) argument for individual scales is
ignored. Values that are out of bounds will be clipped. Whereas the
stat
part of a ggplot layer is typically calculated after scale
transformations, the calculation of the stat
happens before scale
transformation with this function, which can lead to some awkward results.
The suggested workaround is to pre-transform the data for layers with
non-identity stat
parts.
NULL
s are valid list elements and
signal that the default position scale should be used at the position in
the list where the NULL
occurs. Since transformations are applied
before facet scales are initiated, it is not recommended to use a default
position (either the first in the list, or defined outside
facetted_pos_scales()
) scale with a transformation other than
trans = "identity"
(the default).
The x
and y
arguments also
accept a list of two-sided formulas. The left hand side of a formula should
evaluate to a logical
vector. The right hand side of the formula
should evaluate to a position scale, wherein the x
argument accepts
x-position scales and the y
argument accepts y-position scales.
Notably, the left hand side of the formula is evaluated using the tidy
evaluation framework, whereby the data.frame
with the plot's layout
is given priority over the environment in which the formula was created. As
a consequence, variables (columns) that define faceting groups can be
references directly.
A facetted_pos_scales object, instructing a ggplot how to adjust the scales per facet.
ggplot2::scale_x_continuous()
and scale_x_discrete
.
plot <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(colour = Species)) + facet_wrap(Species ~ ., scales = "free_y") # Reversing the y-axis in the second panel. When providing a list of scales, # NULL indicates to use the default, global scale plot + facetted_pos_scales( y = list(NULL, scale_y_continuous(trans = "reverse")) ) # Alternative for specifying scales with formula lists. The LHS can access # columns in the plot's layout. plot + facetted_pos_scales( y = list( Species == "virginica" ~ scale_y_continuous(breaks = c(6, 7)), Species == "versicolor" ~ scale_y_reverse() ) )
plot <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(aes(colour = Species)) + facet_wrap(Species ~ ., scales = "free_y") # Reversing the y-axis in the second panel. When providing a list of scales, # NULL indicates to use the default, global scale plot + facetted_pos_scales( y = list(NULL, scale_y_continuous(trans = "reverse")) ) # Alternative for specifying scales with formula lists. The LHS can access # columns in the plot's layout. plot + facetted_pos_scales( y = list( Species == "virginica" ~ scale_y_continuous(breaks = c(6, 7)), Species == "versicolor" ~ scale_y_reverse() ) )
Takes a ggplot and modifies its facet drawing behaviour such that the widths and heights of panels are set by the user.
force_panelsizes( rows = NULL, cols = NULL, respect = NULL, total_width = NULL, total_height = NULL )
force_panelsizes( rows = NULL, cols = NULL, respect = NULL, total_width = NULL, total_height = NULL )
rows , cols
|
a |
respect |
a |
total_width , total_height
|
an absolute |
Forcing the panel sizes should in theory work regardless of what
facetting choice was made, as long as this function is called after the
facet specification. Even when no facets are specified, ggplot2 defaults to
the ggplot2::facet_null()
specification; a single panel.
force_panelsizes
works by wrapping the original panel drawing
function inside a function that modifies the widths and heights of panel
grobs in the original function's output gtable.
When rows
or cols
are numeric
vectors, panel sizes are
defined as ratios i.e. relative "null" unit
s. rows
and
cols
vectors are repeated or shortened to fit the number of panels
in their direction. When rows
or cols
are NULL
, no
changes are made in that direction.
When respect = NULL
, default behaviour specified elsewhere is
inherited.
No attempt is made to guarantee that the plot fits the output device. The
space
argument in ggplot2::facet_grid()
will be
overruled. When individual panels span multiple rows or columns, this
function may not work as intended.
A forcedsize
S3 object that can be added to a plot.
ggplot2::facet_grid()
ggplot2::facet_wrap()
ggplot2::facet_null()
grid::unit()
ggplot(mtcars, aes(disp, mpg)) + geom_point() + facet_grid(vs ~ am) + force_panelsizes(rows = c(2, 1), cols = c(2, 1))
ggplot(mtcars, aes(disp, mpg)) + geom_point() + facet_grid(vs ~ am) + force_panelsizes(rows = c(2, 1), cols = c(2, 1))
The geom_box()
function offers a more flexible variant of geom_rect()
and
geom_tile()
. Instead of exclusively working with the (x/y)min
/(x/y)max
or (x/y)
/(width/height)
aesthetics, any two out of these four
aesthetics suffice to define a rectangle.
geom_box( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, radius = NULL )
geom_box( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE, radius = NULL )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
linejoin |
Line join style (round, mitre, bevel). |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
radius |
A |
A ggplot2 Layer
object that can be added to a plot.
# Combine any two position aesthetics df <- data.frame( x = c(1.5, 3.5), xmin = c(1, 2), y = c(1.5, 2.5), ymin = c(1, 2) ) ggplot(df) + geom_box(aes(x = x, xmin = xmin, y = y, ymin = ymin)) # Works with partial information for position, as long as two aesthetics # are complete for any observation. df <- data.frame( x = c(1.5, NA, 4), xmin = c(1, 2, NA), width = c(NA, 3, 2), y = c(1.5, 2.5, NA), ymin = c(NA, 2, 3), height = c(1, NA, 3) ) ggplot(df) + geom_box(aes(x = x, xmin = xmin, y = y, ymin = ymin, width = width, height = height)) # Set radius for rounded corners ggplot() + geom_box( aes(x = 1:3, width = rep(1, 3), y = 1:3, height = 3:1), radius = 5 )
# Combine any two position aesthetics df <- data.frame( x = c(1.5, 3.5), xmin = c(1, 2), y = c(1.5, 2.5), ymin = c(1, 2) ) ggplot(df) + geom_box(aes(x = x, xmin = xmin, y = y, ymin = ymin)) # Works with partial information for position, as long as two aesthetics # are complete for any observation. df <- data.frame( x = c(1.5, NA, 4), xmin = c(1, 2, NA), width = c(NA, 3, 2), y = c(1.5, 2.5, NA), ymin = c(NA, 2, 3), height = c(1, NA, 3) ) ggplot(df) + geom_box(aes(x = x, xmin = xmin, y = y, ymin = ymin, width = width, height = height)) # Set radius for rounded corners ggplot() + geom_box( aes(x = 1:3, width = rep(1, 3), y = 1:3, height = 3:1), radius = 5 )
This is a variant of the point geom, wherein overlapping points are given a shared outline. It works by drawing an additional layer of points below a regular layer of points with a thicker stroke.
geom_outline_point( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
geom_outline_point( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
Due to the way this geom is implemented, it handles the alpha
aesthetic pretty ungracefully.
A ggplot Layer
geom_outline_point()
understands the following aesthetics (required aesthetics are in bold):
Learn more about setting these aesthetics in vignette("ggplot2-specs")
.
# A standard plot p <- ggplot(mpg, aes(displ, cty, colour = factor(cyl))) + geom_outline_point(size = 10, stroke = 3) p # The colour of the stroke can be mapped to a scale by setting the # aesthetics to `"stroke_colour"`. p + aes(stroke_colour = factor(cyl)) + scale_colour_hue( aesthetics = "stroke_colour", l = 50 )
# A standard plot p <- ggplot(mpg, aes(displ, cty, colour = factor(cyl))) + geom_outline_point(size = 10, stroke = 3) p # The colour of the stroke can be mapped to a scale by setting the # aesthetics to `"stroke_colour"`. p + aes(stroke_colour = factor(cyl)) + scale_colour_hue( aesthetics = "stroke_colour", l = 50 )
The point path geom is used to make a scatterplot wherein the points are
connected with lines in some order. This geom intends to mimic the
type = 'b'
style of base R line plots.
geom_pointpath( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., na.rm = FALSE, show.legend = NA, arrow = NULL, inherit.aes = TRUE )
geom_pointpath( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., na.rm = FALSE, show.legend = NA, arrow = NULL, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
arrow |
Arrow specification as created by
|
inherit.aes |
If |
The mult
is a numeric value to
scale the proportion of gaps in the line around points.
While the need for this geom is not very apparent, since it can be approximated in a variety of ways, the trick up its sleeve is that it dynamically adapts the inter-point segments so these don't deform under different aspect ratios or device sizes.
A Layer ggproto object.
geom_pointpath()
understands the following
aesthetics (required aesthetics are in bold):
x
y
alpha
colour
group
shape
size
stroke
linewidth
linetype
mult
ggplot(pressure, aes(temperature, pressure)) + geom_pointpath() # Using geom_pointpath as annotation ggplot() + annotate( "pointpath", x = c(1, 0.32, 0.31, -0.12, -0.81, -0.4, -0.81, -0.12, 0.31, 0.32, 1), y = c(0, 0.24, 0.95, 0.38, 0.59, 0, -0.59, -0.38, -0.95, -0.24, 0) )
ggplot(pressure, aes(temperature, pressure)) + geom_pointpath() # Using geom_pointpath as annotation ggplot() + annotate( "pointpath", x = c(1, 0.32, 0.31, -0.12, -0.81, -0.4, -0.81, -0.12, 0.31, 0.32, 1), y = c(0, 0.24, 0.95, 0.38, 0.59, 0, -0.59, -0.38, -0.95, -0.24, 0) )
geom_polygonraster
takes data that describes a raster with pixels of
the same size and reparametrises the data as a polygon. This allows for more
flexible transformations of the data, but comes at an efficiency cost.
geom_polygonraster( mapping = NULL, data = NULL, stat = "identity", position = position_lineartrans(), ..., hjust = 0.5, vjust = 0.5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
geom_polygonraster( mapping = NULL, data = NULL, stat = "identity", position = position_lineartrans(), ..., hjust = 0.5, vjust = 0.5, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
hjust , vjust
|
horizontal and vertical justification of the grob. Each justification value should be a number between 0 and 1. Defaults to 0.5 for both, centering each pixel over its data location. |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
For each pixel in a raster, makes a vertex for each of the four
corner points. These coordinates can then by transformed by
coord
-functions such as ggplot2::coord_polar()
or
position
-functions such as
position_lineartrans()
. Currently substitutes group
aesthetics right before drawing in favour of pixel identifiers.
A Layer ggproto object.
geom_raster()
understands the following aesthetics (required
aesthetics are in bold):
x
y
fill
alpha
group
# Combining with coord_polar() ggplot(faithfuld, aes(waiting, eruptions)) + geom_polygonraster(aes(fill = density)) + coord_polar() # Combining with linear transformations df <- data.frame(x = row(volcano)[TRUE], y = col(volcano)[TRUE], z = volcano[TRUE]) ggplot(df, aes(x, y, fill = z)) + geom_polygonraster(position = position_lineartrans(angle = 30, shear = c(1, 0)))
# Combining with coord_polar() ggplot(faithfuld, aes(waiting, eruptions)) + geom_polygonraster(aes(fill = density)) + coord_polar() # Combining with linear transformations df <- data.frame(x = row(volcano)[TRUE], y = col(volcano)[TRUE], z = volcano[TRUE]) ggplot(df, aes(x, y, fill = z)) + geom_polygonraster(position = position_lineartrans(angle = 30, shear = c(1, 0)))
Like rug plots display data points of a 2D plot as lines in the margins, this function plots rectangles in the margins. Rectangular rugs are convenient for displaying one-dimensional, ranged annotations for two-dimensional plots.
geom_rectmargin( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., outside = FALSE, sides = "bl", length = unit(0.03, "npc"), linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_tilemargin( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., outside = FALSE, sides = "bl", length = unit(0.03, "npc"), linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
geom_rectmargin( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., outside = FALSE, sides = "bl", length = unit(0.03, "npc"), linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE ) geom_tilemargin( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., outside = FALSE, sides = "bl", length = unit(0.03, "npc"), linejoin = "mitre", na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
outside |
|
sides |
A |
length |
A |
linejoin |
Line join style (round, mitre, bevel). |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
By default, scales are expanded 5\
whereas the rug rectangles will occupy 3\
default. The geom_rectmargin()
and geom_tilemargin()
versions do the
same thing, but are parametrised differently; see
geom_rect()
.
These functions do not have hard-coded required aesthetics, since the x and y directions can be omitted by not choosing a side in the corresponding direction, i.e. y-direction variables are omitted when plotting the rug only on the top and/or bottom. This can result in errors when the aesthetics are not specified appropriately, so some caution is advised.
A Layer ggproto object.
geom_rectmargin()
requires either one of the following
sets of aesthetics, but also can use both:
xmin
xmax
and/or:
ymin
ymax
geom_tilemargin()
requires either one of the following
sets of aesthetics, but can also use both:
x
width
and/or:
y
height
Furthermore, geom_rectmargin()
and geom_tilemargin()
also
understand these shared aesthetics:
alpha
colour
fill
group
linetype
size
ggplot2::geom_rug()
, geom_rect()
,
ggplot2::geom_tile()
# geom_rectmargin() is parameterised by the four corners df <- data.frame( xmin = c(1, 5), xmax = c(2, 7), ymin = c(1, 2), ymax = c(2, 4), fill = c("A", "B") ) ggplot(df, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill)) + geom_rect() + geom_rectmargin() # geom_tilemargin() is parameterised by center and size df <- data.frame( x = c(1, 4), y = c(1, 2), width = c(2, 1), height = c(1, 2), fill = c("A", "B") ) ggplot(df, aes(x, y, width = width, height = height, fill = fill)) + geom_tile() + geom_tilemargin()
# geom_rectmargin() is parameterised by the four corners df <- data.frame( xmin = c(1, 5), xmax = c(2, 7), ymin = c(1, 2), ymax = c(2, 4), fill = c("A", "B") ) ggplot(df, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill = fill)) + geom_rect() + geom_rectmargin() # geom_tilemargin() is parameterised by center and size df <- data.frame( x = c(1, 4), y = c(1, 2), width = c(2, 1), height = c(1, 2), fill = c("A", "B") ) ggplot(df, aes(x, y, width = width, height = height, fill = fill)) + geom_tile() + geom_tilemargin()
Similar to geom_text()
, this geom also generates text but places the
text at an angle so that the text seems aimed towards a point defined by
[xend, yend]
.
geom_text_aimed( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, flip_upsidedown = TRUE, check_overlap = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
geom_text_aimed( mapping = NULL, data = NULL, stat = "identity", position = "identity", ..., parse = FALSE, nudge_x = 0, nudge_y = 0, flip_upsidedown = TRUE, check_overlap = FALSE, na.rm = FALSE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
stat |
The statistical transformation to use on the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer.
Cannot be jointy specified with
|
... |
Other arguments passed on to
|
parse |
If |
nudge_x , nudge_y
|
Horizontal and vertical adjustment to nudge labels by.
Useful for offsetting text from points, particularly on discrete scales.
Cannot be jointly specified with |
flip_upsidedown |
A |
check_overlap |
If |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
The calculated angle is such that the text will be parallel to a
line passing through the coordinates [x, y]
and [xend, yend]
.
The calculated angle is added to the angle
angle aesthetic, so that
you can set text perpendicular to that line by setting angle = 90
.
These angles are calculated in absolute coordinates, meaning that resizing
the plot will retain the same appearance.
A ggplot2 Layer
that can be added to a plot.
geom_text_aimed()
understands the following aesthetics (required aesthetics are in bold):
Learn more about setting these aesthetics in vignette("ggplot2-specs")
.
When using this geom to aim text at the centre of a polar plot, make sure the radius range does not have close to zero width.
# Point all labels to upper right corner ggplot(mtcars, aes(mpg, wt)) + geom_text_aimed(aes(label = rownames(mtcars)), xend = Inf, yend = Inf) # Point all labels to center of polar plot ggplot(mpg, aes(manufacturer)) + geom_bar(width = 1, aes(fill = manufacturer), show.legend = FALSE) + geom_text_aimed(aes(label = manufacturer), hjust = 0, stat = "count", nudge_y = 2) + scale_x_discrete(labels = NULL) + coord_polar()
# Point all labels to upper right corner ggplot(mtcars, aes(mpg, wt)) + geom_text_aimed(aes(label = rownames(mtcars)), xend = Inf, yend = Inf) # Point all labels to center of polar plot ggplot(mpg, aes(manufacturer)) + geom_bar(width = 1, aes(fill = manufacturer), show.legend = FALSE) + geom_text_aimed(aes(label = manufacturer), hjust = 0, stat = "count", nudge_y = 2) + scale_x_discrete(labels = NULL) + coord_polar()
ggh4x relies on the extension mechanism of ggplot2 through ggproto class objects, which allows cross-package inheritance of objects such as geoms, stats, facets, scales and coordinate systems. These objects can be ignored by users for the purpose of making plots, since interacting with these objects is preferred through various geom_, stat_, facet_, coord_ and scale_ functions.
This is a convenience function to allow layer objects, such as geoms, to take
a subset of the data in the main ggplot()
call, without storing a
duplicate of the subset in the ggplot object.
ggsubset(rowtest = NULL, omit = NULL)
ggsubset(rowtest = NULL, omit = NULL)
rowtest |
logical |
omit |
a |
ggsubset
is a wrapper around subset.data.frame
where
the subset
argument is set to rowtest
and the select
argument to -omit
. Since the data
argument in the
layer()
function can take a function with one argument, we can pass
the function returned from ggsubset
as that argument to subset the
data by rows.
A function that takes a data.frame
as argument and returns a
subset of that data.frame
according to rowtest
See ggplot2::layer()
, specifically the data
argument. See subset.data.frame()
for the internal
function.
ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(data = ggsubset(Species == "setosa"))
ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point(data = ggsubset(Species == "setosa"))
This axis guide is probably best described as
ggplot2::annotation_logticks()
but implemented as a guide instead
of a geom. The tick marks probably best suit log10 transformations.
The function is questioned due to
a possible migration of guide functions after ggplot2 releases a new guide
system.
guide_axis_logticks( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, position = waiver(), prescaled = FALSE, trunc_lower = NULL, trunc_upper = NULL, colour = NULL, color = NULL, base = waiver() )
guide_axis_logticks( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, position = waiver(), prescaled = FALSE, trunc_lower = NULL, trunc_upper = NULL, colour = NULL, color = NULL, base = waiver() )
title |
A character string or expression indicating a title of guide.
If |
check.overlap |
silently remove overlapping labels, (recursively) prioritizing the first, last, and middle labels. |
angle |
Compared to setting the angle in
|
n.dodge |
The number of rows (for vertical axes) or columns (for horizontal axes) that should be used to render the labels. This is useful for displaying labels that would otherwise overlap. |
order |
A positive |
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
prescaled |
A |
trunc_lower , trunc_upper
|
The lower and upper range of the truncated axis:
|
colour , color
|
A |
base |
When this is provided, the guide takes this as the base for the
log transformation instead of trying to guess the base. It is recommended
to use this argument if the base is not |
An axis_logticks guide class object.
This axis guide uses the following the theme elements:
ggh4x.axis.ticks.length.minor
An rel()
object to set the size of minor ticks relative to the
length of major ticks (axis.ticks.length
). Defaults to rel(2/3)
.
ggh4x.axis.ticks.length.mini
An rel()
object to set the size of smallest ticks, also relative to
the length of major ticks (axis.ticks.length
). Defaults to
rel(1/3)
.
Other axis-guides:
guide_axis_manual()
,
guide_axis_minor()
,
guide_axis_nested()
,
guide_axis_scalebar()
,
guide_axis_truncated()
# The guide works well out of the box with log10 scales p <- ggplot(pressure, aes(temperature, pressure)) + geom_line() p + scale_y_log10(guide = "axis_logticks") # If the data is already transformed, you can set 'prescaled' to TRUE ggplot(pressure, aes(temperature, log10(pressure))) + geom_line() + guides(y = guide_axis_logticks(prescaled = TRUE)) # The lenghts of the log-ticks are controlled by the theme relative to the # major ticks. p + scale_y_log10(guide = "axis_logticks") + theme( axis.ticks.length.y = unit(1, "cm"), ggh4x.axis.ticks.length.minor = rel(0.55), ggh4x.axis.ticks.length.mini = rel(0.1) )
# The guide works well out of the box with log10 scales p <- ggplot(pressure, aes(temperature, pressure)) + geom_line() p + scale_y_log10(guide = "axis_logticks") # If the data is already transformed, you can set 'prescaled' to TRUE ggplot(pressure, aes(temperature, log10(pressure))) + geom_line() + guides(y = guide_axis_logticks(prescaled = TRUE)) # The lenghts of the log-ticks are controlled by the theme relative to the # major ticks. p + scale_y_log10(guide = "axis_logticks") + theme( axis.ticks.length.y = unit(1, "cm"), ggh4x.axis.ticks.length.minor = rel(0.55), ggh4x.axis.ticks.length.mini = rel(0.1) )
This axis allows a greater degree of control than the default axes guides. In
particular, this axis allows setting break positions and labels independently
from the scale and is not bound by the same constraints as secondary axes.
Additionally, label attributes may be set in parallel to the labels
themselves, circumventing the unsupported vectorised input to
element_text()
.
The function is questioned due to
a possible migration of guide functions after ggplot2 releases a new guide
system.
guide_axis_manual( title = waiver(), breaks = waiver(), labels = waiver(), label_family = NULL, label_face = NULL, label_colour = NULL, label_size = NULL, label_hjust = NULL, label_vjust = NULL, label_lineheight = NULL, label_color = NULL, label_margin = NULL, check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() )
guide_axis_manual( title = waiver(), breaks = waiver(), labels = waiver(), label_family = NULL, label_face = NULL, label_colour = NULL, label_size = NULL, label_hjust = NULL, label_vjust = NULL, label_lineheight = NULL, label_color = NULL, label_margin = NULL, check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() )
title |
A character string or expression indicating a title of guide.
If |
breaks |
One of the following ways to parametrise the tick and label positions:
|
labels |
One of the following ways to dictate the labels:
|
label_family , label_face , label_colour , label_size , label_hjust , label_vjust , label_lineheight , label_color , label_margin
|
Arguments passed down to the label constructor. See
|
check.overlap |
silently remove overlapping labels, (recursively) prioritizing the first, last, and middle labels. |
angle |
Compared to setting the angle in
|
n.dodge |
The number of rows (for vertical axes) or columns (for horizontal axes) that should be used to render the labels. This is useful for displaying labels that would otherwise overlap. |
order |
A positive |
colour , color
|
A |
trunc_lower , trunc_upper
|
The lower and upper range of the truncated axis:
|
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
An axis_manual guide class object.
Other axis-guides:
guide_axis_logticks()
,
guide_axis_minor()
,
guide_axis_nested()
,
guide_axis_scalebar()
,
guide_axis_truncated()
ggplot(iris, aes(Species, Sepal.Width)) + geom_boxplot(aes(fill = Species)) + guides(x = guide_axis_manual( label_colour = scales::hue_pal()(3), label_face = c("bold", "italic", "plain"), labels = toupper )) # Using the manual axis to annotate some specific point ggplot(pressure, aes(temperature, pressure)) + geom_point() + geom_hline(yintercept = 300, linetype = 2, colour = "blue") + guides(y.sec = guide_axis_manual(breaks = 300, labels = "some\nthreshold", label_colour = "blue"))
ggplot(iris, aes(Species, Sepal.Width)) + geom_boxplot(aes(fill = Species)) + guides(x = guide_axis_manual( label_colour = scales::hue_pal()(3), label_face = c("bold", "italic", "plain"), labels = toupper )) # Using the manual axis to annotate some specific point ggplot(pressure, aes(temperature, pressure)) + geom_point() + geom_hline(yintercept = 300, linetype = 2, colour = "blue") + guides(y.sec = guide_axis_manual(breaks = 300, labels = "some\nthreshold", label_colour = "blue"))
These are similar the the normal axis guides for position scales, but also place tickmarks at minor break positions. The function is questioned due to a possible migration of guide functions after ggplot2 releases a new guide system.
guide_axis_minor( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() )
guide_axis_minor( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() )
title |
A character string or expression indicating a title of guide.
If |
check.overlap |
silently remove overlapping labels, (recursively) prioritizing the first, last, and middle labels. |
angle |
Compared to setting the angle in
|
n.dodge |
The number of rows (for vertical axes) or columns (for horizontal axes) that should be used to render the labels. This is useful for displaying labels that would otherwise overlap. |
order |
A positive |
colour , color
|
A |
trunc_lower , trunc_upper
|
The lower and upper range of the truncated axis:
|
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
An axis_minor guide class object.
This axis guide uses the following the theme elements:
ggh4x.axis.ticks.length.minor
An rel()
object to set the size of minor ticks relative to the
length of major ticks (axis.ticks.length
). Defaults to rel(2/3)
.
Other axis-guides:
guide_axis_logticks()
,
guide_axis_manual()
,
guide_axis_nested()
,
guide_axis_scalebar()
,
guide_axis_truncated()
# Using the minor breaks axis p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point() p + scale_y_continuous(guide = "axis_minor") # Minor break positions are still controlled by the scale p + scale_y_continuous(guide = "axis_minor", minor_breaks = seq(4, 8, by = 0.2)) # Minor tick length is controlled relative to major ticks p + scale_y_continuous(guide = "axis_minor") + theme(ggh4x.axis.ticks.length.minor = rel(0.1))
# Using the minor breaks axis p <- ggplot(iris, aes(Sepal.Width, Sepal.Length)) + geom_point() p + scale_y_continuous(guide = "axis_minor") # Minor break positions are still controlled by the scale p + scale_y_continuous(guide = "axis_minor", minor_breaks = seq(4, 8, by = 0.2)) # Minor tick length is controlled relative to major ticks p + scale_y_continuous(guide = "axis_minor") + theme(ggh4x.axis.ticks.length.minor = rel(0.1))
Discrete position scales containing interacting factors can be visualised more clearly with a nested axis guide. Nested axis guides separate labels based on a delimiter and groups identical later labels, indicating the grouping with a line spanning the earlier labels. The function is questioned due to a possible migration of guide functions after ggplot2 releases a new guide system.
guide_axis_nested( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, position = waiver(), delim = waiver(), inv = FALSE, trunc_lower = NULL, trunc_upper = NULL, colour = NULL, color = NULL, extend = 0.5 )
guide_axis_nested( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, position = waiver(), delim = waiver(), inv = FALSE, trunc_lower = NULL, trunc_upper = NULL, colour = NULL, color = NULL, extend = 0.5 )
title |
A character string or expression indicating a title of guide.
If |
check.overlap |
silently remove overlapping labels, (recursively) prioritizing the first, last, and middle labels. |
angle |
Compared to setting the angle in
|
n.dodge |
The number of rows (for vertical axes) or columns (for horizontal axes) that should be used to render the labels. This is useful for displaying labels that would otherwise overlap. |
order |
A positive |
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
delim |
A |
inv |
A |
trunc_lower , trunc_upper
|
The lower and upper range of the truncated axis:
|
colour , color
|
A |
extend |
A |
The guide itself makes no effort to group and order labels. To get nice groupings, consider re-ordering the levels of factor variables, or try setting the 'breaks' argument of a scale appropriately.
A axis_nested guide class object.
This axis guide uses the following the theme elements:
ggh4x.axis.nestline.x/y
An element_line()
object to alter the display of the line
separating different layers of labels.
ggh4x.axis.nesttext.x/y
An element_text()
object to differentiate text higher up in the
hierarchy, from the text closest to the axis line.
ggplot2::guide_axis()
for the classic axis
documentation. weave_factors()
for an alternative to
interaction()
.
Other axis-guides:
guide_axis_logticks()
,
guide_axis_manual()
,
guide_axis_minor()
,
guide_axis_scalebar()
,
guide_axis_truncated()
# The defaults are suited for interaction variables ggplot(mpg, aes(interaction(cyl, class), hwy)) + geom_boxplot() + scale_x_discrete(guide = "axis_nested") # Control where labels are cut with the delim argument ggplot(mpg, aes(interaction(cyl, class, sep = "~!~"), hwy)) + geom_boxplot() + scale_x_discrete(guide = guide_axis_nested(delim = "!")) # The nesting lines inherit looks from axis ticks ggplot(mpg, aes(interaction(cyl, class), hwy)) + geom_boxplot() + scale_x_discrete(guide = "axis_nested") + theme(axis.ticks = element_line(colour = "red")) # The looks can be controlled independently by setting `ggh4x.axis.nestline` ggplot(mpg, aes(interaction(cyl, class), hwy)) + geom_boxplot() + scale_x_discrete(guide = "axis_nested") + theme(ggh4x.axis.nestline = element_line(linetype = 2))
# The defaults are suited for interaction variables ggplot(mpg, aes(interaction(cyl, class), hwy)) + geom_boxplot() + scale_x_discrete(guide = "axis_nested") # Control where labels are cut with the delim argument ggplot(mpg, aes(interaction(cyl, class, sep = "~!~"), hwy)) + geom_boxplot() + scale_x_discrete(guide = guide_axis_nested(delim = "!")) # The nesting lines inherit looks from axis ticks ggplot(mpg, aes(interaction(cyl, class), hwy)) + geom_boxplot() + scale_x_discrete(guide = "axis_nested") + theme(axis.ticks = element_line(colour = "red")) # The looks can be controlled independently by setting `ggh4x.axis.nestline` ggplot(mpg, aes(interaction(cyl, class), hwy)) + geom_boxplot() + scale_x_discrete(guide = "axis_nested") + theme(ggh4x.axis.nestline = element_line(linetype = 2))
This axis guides draws a scale bar to indicate a distance rather than mark absolute values. The function is questioned due to a possible migration of guide functions after ggplot2 releases a new guide system.
guide_axis_scalebar( title = waiver(), size = NULL, label = NULL, colour = NULL, color = NULL, just = 1, position = waiver() )
guide_axis_scalebar( title = waiver(), size = NULL, label = NULL, colour = NULL, color = NULL, just = 1, position = waiver() )
title |
A character string or expression indicating a title of guide.
If |
size |
A |
label |
A |
colour , color
|
A |
just |
A |
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
It is discouraged to use this guide in combination with a scale transformation.
A axis_scalebar
guide class object.
This axis guide has an alternative understanding of the following theme elements:
axis.ticks.*
An element_line()
to draw the scale bar itself.
axis.ticks.length.*
A unit()
indicating how far the scale bar should be placed from the
plot panel. Can be a negative unit to place the scale bar inside the
plot panel.
axis.text.*
The hjust
and vjust
parameters are used to justify the text along
the scale bar, instead of along itself, in the x
and y
directions
respectively.
Other axis-guides:
guide_axis_logticks()
,
guide_axis_manual()
,
guide_axis_minor()
,
guide_axis_nested()
,
guide_axis_truncated()
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Guide as secondary axis p + guides(x.sec = "axis_scalebar") # Customising size and label p + guides(x.sec = guide_axis_scalebar(size = 0.5, label = "0.5 litre")) # Placing the scale bar on top of the plotting panel p + guides(x.sec = guide_axis_scalebar(just = 0.95)) + theme(axis.ticks.length.x.top = unit(-2, "lines")) # Adding arrows through the axis.ticks theme element p + guides(y.sec = guide_axis_scalebar(size = 10, label = "10\nmpg")) + theme(axis.ticks.y.right = element_line(arrow = arrow(ends = "both")))
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Guide as secondary axis p + guides(x.sec = "axis_scalebar") # Customising size and label p + guides(x.sec = guide_axis_scalebar(size = 0.5, label = "0.5 litre")) # Placing the scale bar on top of the plotting panel p + guides(x.sec = guide_axis_scalebar(just = 0.95)) + theme(axis.ticks.length.x.top = unit(-2, "lines")) # Adding arrows through the axis.ticks theme element p + guides(y.sec = guide_axis_scalebar(size = 10, label = "10\nmpg")) + theme(axis.ticks.y.right = element_line(arrow = arrow(ends = "both")))
This axis guide is similar to the normal axis guides for position scales, but
can shorten the axis line that is being drawn. The guide_axis_colour()
function is the same but with different defaults for the truncation that do
not truncate the axis. Axis truncation and recolouring is supported
throughout axes in ggh4x.
The function is questioned due to
a possible migration of guide functions after ggplot2 releases a new guide
system.
guide_axis_truncated( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = min, trunc_upper = max, position = waiver() ) guide_axis_colour( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() ) guide_axis_color( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() )
guide_axis_truncated( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = min, trunc_upper = max, position = waiver() ) guide_axis_colour( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() ) guide_axis_color( title = waiver(), check.overlap = FALSE, angle = NULL, n.dodge = 1, order = 0, colour = NULL, color = NULL, trunc_lower = NULL, trunc_upper = NULL, position = waiver() )
title |
A character string or expression indicating a title of guide.
If |
check.overlap |
silently remove overlapping labels, (recursively) prioritizing the first, last, and middle labels. |
angle |
Compared to setting the angle in
|
n.dodge |
The number of rows (for vertical axes) or columns (for horizontal axes) that should be used to render the labels. This is useful for displaying labels that would otherwise overlap. |
order |
A positive |
colour , color
|
A |
trunc_lower , trunc_upper
|
The lower and upper range of the truncated axis:
|
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
An axis_ggh4x guide class object.
Other axis-guides:
guide_axis_logticks()
,
guide_axis_manual()
,
guide_axis_minor()
,
guide_axis_nested()
,
guide_axis_scalebar()
# Make a plot p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme(axis.line = element_line(colour = "black")) # Setting the default truncated axis p + guides(x = "axis_truncated") # Truncating in data units p + guides(x = guide_axis_truncated( trunc_lower = 2.5, trunc_upper = 4.5 )) # Truncate by setting units p + guides(x = guide_axis_truncated( trunc_lower = unit(0.1, "npc"), trunc_upper = unit(0.9, "npc") )) # Truncating with functions p + guides(x = guide_axis_truncated( trunc_lower = function(x) {x - 0.2}, trunc_upper = function(x) {x + 0.2} )) # Recolouring the axes outside the theme p + guides(x = guide_axis_colour(colour = "red"), y = guide_axis_colour(colour = "blue"))
# Make a plot p <- ggplot(mtcars, aes(wt, mpg)) + geom_point() + theme(axis.line = element_line(colour = "black")) # Setting the default truncated axis p + guides(x = "axis_truncated") # Truncating in data units p + guides(x = guide_axis_truncated( trunc_lower = 2.5, trunc_upper = 4.5 )) # Truncate by setting units p + guides(x = guide_axis_truncated( trunc_lower = unit(0.1, "npc"), trunc_upper = unit(0.9, "npc") )) # Truncating with functions p + guides(x = guide_axis_truncated( trunc_lower = function(x) {x - 0.2}, trunc_upper = function(x) {x + 0.2} )) # Recolouring the axes outside the theme p + guides(x = guide_axis_colour(colour = "red"), y = guide_axis_colour(colour = "blue"))
Visual representation of a discrete variable with hierarchical relationships
between members, like those detailed in
scale_(x|y)_dendrogram)()
.
guide_dendro( title = waiver(), check.overlap = FALSE, n.dodge = 1, order = 0, position = waiver(), label = TRUE, trunc_lower = NULL, trunc_upper = NULL, colour = NULL, color = NULL, dendro = waiver() )
guide_dendro( title = waiver(), check.overlap = FALSE, n.dodge = 1, order = 0, position = waiver(), label = TRUE, trunc_lower = NULL, trunc_upper = NULL, colour = NULL, color = NULL, dendro = waiver() )
title |
A character string or expression indicating a title of guide.
If |
check.overlap |
silently remove overlapping labels, (recursively) prioritizing the first, last, and middle labels. |
n.dodge |
The number of rows (for vertical axes) or columns (for horizontal axes) that should be used to render the labels. This is useful for displaying labels that would otherwise overlap. |
order |
A positive |
position |
Where this guide should be drawn: one of top, bottom, left, or right. |
label |
A |
trunc_lower , trunc_upper
|
The lower and upper range of the truncated axis:
|
colour , color
|
A |
dendro |
Relevant plotting data for a dendrogram such as those returned
by |
The dendrogram guide inherits graphical elements from the
axis.ticks
theme element. However, the size of the dendrogram is set
to 10 times the axis.ticks.length
theme element.
A dendroguide class object.
clust <- hclust(dist(USArrests), "ave") # Melting USArrests df <- data.frame( State = rownames(USArrests)[row(USArrests)], variable = colnames(USArrests)[col(USArrests)], value = unname(do.call(c, USArrests)) ) # The guide function can be used to customise the axis g <- ggplot(df, aes(variable, State, fill = value)) + geom_raster() + scale_y_dendrogram(hclust = clust, guide = guide_dendro(n.dodge = 2)) # The looks of the dendrogram are controlled through ticks g + theme(axis.ticks = element_line(colour = "red")) # The size of the dendrogram is controlled through tick size * 10 g + theme(axis.ticks.length = unit(5, "pt"))
clust <- hclust(dist(USArrests), "ave") # Melting USArrests df <- data.frame( State = rownames(USArrests)[row(USArrests)], variable = colnames(USArrests)[col(USArrests)], value = unname(do.call(c, USArrests)) ) # The guide function can be used to customise the axis g <- ggplot(df, aes(variable, State, fill = value)) + geom_raster() + scale_y_dendrogram(hclust = clust, guide = guide_dendro(n.dodge = 2)) # The looks of the dendrogram are controlled through ticks g + theme(axis.ticks = element_line(colour = "red")) # The size of the dendrogram is controlled through tick size * 10 g + theme(axis.ticks.length = unit(5, "pt"))
This type of legend shows colour and fill mappings as coloured text. It does
not draw keys as guide_legend()
does.
The function is questioned due to
a possible migration of guide functions after ggplot2 releases a new guide
system.
guide_stringlegend( title = waiver(), title.position = NULL, title.theme = NULL, title.hjust = NULL, title.vjust = NULL, label.theme = NULL, label.hjust = NULL, label.vjust = NULL, family = NULL, face = NULL, size = NULL, spacing.x = NULL, spacing.y = NULL, spacing = NULL, default.units = "pt", direction = NULL, nrow = NULL, ncol = NULL, byrow = FALSE, reverse = FALSE, order = 0, ... )
guide_stringlegend( title = waiver(), title.position = NULL, title.theme = NULL, title.hjust = NULL, title.vjust = NULL, label.theme = NULL, label.hjust = NULL, label.vjust = NULL, family = NULL, face = NULL, size = NULL, spacing.x = NULL, spacing.y = NULL, spacing = NULL, default.units = "pt", direction = NULL, nrow = NULL, ncol = NULL, byrow = FALSE, reverse = FALSE, order = 0, ... )
title |
A character string or expression indicating a title of guide.
If |
title.position |
A character string indicating the position of a title.
One of |
title.theme |
A theme object for rendering the title text. |
title.hjust , title.vjust
|
A number specifying horizontal and vertical justification of the title text. |
label.theme |
A theme object for rendering the legend text. |
label.hjust , label.vjust
|
A numer specifying horizontal and vertical justification of the legend text. |
family |
A |
face |
A |
size |
A |
spacing.x , spacing.y , spacing
|
A |
default.units |
A |
direction |
A character string indicating the direction of the guide. One of "horizontal" or "vertical." |
nrow , ncol
|
The desired number of rows and column of legends respectively. |
byrow |
logical. If |
reverse |
logical. If |
order |
positive integer less than 99 that specifies the order of this guide among multiple guides. This controls the order in which multiple guides are displayed, not the contents of the guide itself. If 0 (default), the order is determined by a secret algorithm. |
... |
ignored. |
A guide
, stringlegend
S3 object.
p <- ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = manufacturer)) # String legend can be set in the `guides()` function p + guides(colour = guide_stringlegend(ncol = 2)) # The string legend can also be set as argument to the scale p + scale_colour_viridis_d(guide = "stringlegend")
p <- ggplot(mpg, aes(displ, hwy)) + geom_point(aes(colour = manufacturer)) # String legend can be set in the `guides()` function p + guides(colour = guide_stringlegend(ncol = 2)) # The string legend can also be set as argument to the scale p + scale_colour_viridis_d(guide = "stringlegend")
The purpose of this function is to construct a secondary axis with a projection function.
help_secondary( data = NULL, primary = c(0, 1), secondary = c(0, 1), method = c("range", "max", "fit", "ccf", "sortfit"), na.rm = TRUE, ... )
help_secondary( data = NULL, primary = c(0, 1), secondary = c(0, 1), method = c("range", "max", "fit", "ccf", "sortfit"), na.rm = TRUE, ... )
data |
A |
primary , secondary
|
An expression that is evaluated in the context of
the |
method |
One of the following:
|
na.rm |
A |
... |
Arguments passed on to
|
The intent is to run this function before starting a plot. The
output of the function is a secondary axis wherein the trans
argument of
sec_axis()
is populated by an appropriate transformation. In addition,
the output also contains a output$proj()
function that helps transform the
secondary data.
An AxisSecondary
ggproto object with a proj
method for projecting
secondary data.
# Run the secondary axis helper sec <- help_secondary(economics, primary = unemploy, secondary = psavert) # Making primary plot p <- ggplot(economics, aes(date)) + geom_line(aes(y = unemploy), colour = "blue") # For the secondary data, later we use the `proj` function from the helper p <- p + geom_line(aes(y = sec$proj(psavert)), colour = "red") # We feed the scale the secondary axis p + scale_y_continuous(sec.axis = sec) # Setup cross-correlated data set.seed(42) n <- 100 lag <- 20 dat <- cumsum(rnorm(n + lag)) df <- data.frame( x = seq_len(n), y1 = head(dat, n), y2 = 10 + tail(dat, n) * 5 # offset and scale y2 ) # Choosing the cross-correlation function method. sec <- help_secondary(df, y1, y2, method = "ccf") ggplot(df, aes(x)) + geom_line(aes(y = y1), colour = "blue") + geom_line(aes(y = sec$proj(y2)), colour = "red") + scale_y_continuous(sec.axis = sec)
# Run the secondary axis helper sec <- help_secondary(economics, primary = unemploy, secondary = psavert) # Making primary plot p <- ggplot(economics, aes(date)) + geom_line(aes(y = unemploy), colour = "blue") # For the secondary data, later we use the `proj` function from the helper p <- p + geom_line(aes(y = sec$proj(psavert)), colour = "red") # We feed the scale the secondary axis p + scale_y_continuous(sec.axis = sec) # Setup cross-correlated data set.seed(42) n <- 100 lag <- 20 dat <- cumsum(rnorm(n + lag)) df <- data.frame( x = seq_len(n), y1 = head(dat, n), y2 = 10 + tail(dat, n) * 5 # offset and scale y2 ) # Choosing the cross-correlation function method. sec <- help_secondary(df, y1, y2, method = "ccf") ggplot(df, aes(x)) + geom_line(aes(y = y1), colour = "blue") + geom_line(aes(y = sec$proj(y2)), colour = "red") + scale_y_continuous(sec.axis = sec)
One-dimensional ranged data in the x-direction is segregated in the y-direction such that no overlap in two-dimensional space occurs. This positioning works best when no relevant information is plotted in the y-direction.
position_disjoint_ranges(extend = 1, stepsize = 1)
position_disjoint_ranges(extend = 1, stepsize = 1)
extend |
a |
stepsize |
a |
An object is considered disjoint from a second object when the range
between their xmin
and xmax
coordinates don't overlap.
Objects that overlap are assigned to different bins in the y-direction,
whereby lower bins are filled first. This way, information in the
x-direction is preserved and different objects can be discerned.
Note that this positioning is only particularly useful when y-coordinates
do not encode relevant information. Geoms that pair well with this
positioning are geom_rect()
and
ggplot2::geom_tile()
.
This positioning function was inspired by the disjointBins()
function in the IRanges
package, but has been written such that it
accepts any numeric input next to solely integer input.
A PositionDisjointRanges object.
The disjointBins
function the Bioconductor IRanges package.
# Even though geom_tile() is parametrised by middle-x values, it is # internally converted to xmin, xmax, ymin, ymax parametrisation so the # positioning still works. ggplot() + geom_tile(aes(x = rnorm(200), y = 0), width = 0.2, height = 0.9, position = position_disjoint_ranges(extend = 0.1))
# Even though geom_tile() is parametrised by middle-x values, it is # internally converted to xmin, xmax, ymin, ymax parametrisation so the # positioning still works. ggplot() + geom_tile(aes(x = rnorm(200), y = 0), width = 0.2, height = 0.9, position = position_disjoint_ranges(extend = 0.1))
Transforms coordinates in two dimensions in a linear manner for layers that
have an x
and y
parametrisation.
position_lineartrans(scale = c(1, 1), shear = c(0, 0), angle = 0, M = NULL)
position_lineartrans(scale = c(1, 1), shear = c(0, 0), angle = 0, M = NULL)
scale |
A |
shear |
A |
angle |
A |
M |
A |
Linear transformation matrices are 2
x 2
real
matrices. The 'scale
', 'shear
' and 'rotation
'
arguments are convenience arguments to construct a transformation matrix.
These operations occur in the order: scaling - shearing - rotating. To
apply the transformations in another order, build a custom 'M
'
argument.
For some common transformations, you can find appropriate matrices for the
'M
' argument below.
A PositionLinearTrans ggproto object.
An
identity transformation, or returning the original coordinates, can be
performed by using the following transformation matrix: | 1 0 |
| 0 1 |
or M <- matrix(c(1, 0, 0, 1), 2)
A scaling transformation multiplies the dimension of
an object by some amount. An example transformation matrix for scaling
everything by a factor 2: | 2 0 |
| 0 2 |
or
M <- matrix(c(2, 0, 0, 2), 2)
Similar
to scaling, squeezing multiplies the dimensions by some amount that is
unequal for the x
and y
coordinates. For example, squeezing
y
by half and expanding x
by two:
| | 2 |
0 |
| | |||
| | 0
|
0.5 |
| | |||
or M <- matrix(c(2, 0, 0, 0.5), 2)
Mirroring the coordinates around one of the axes. Reflecting around the x-axis:
| |
1 |
0 |
| | |||
| | 0 |
-1 |
| | |||
or M <- matrix(c(1, 0, 0, -1), 2)
Reflecting around the y-axis:
| |
-1 |
0 |
| | |||
| | 0 |
1 |
| | |||
or M <- matrix(c(-1, 0, 0, 1), 2)
For projecting the coordinates on one of the axes,
while collapsing everything from the other axis. Projecting onto the
y
-axis:
| | 0 |
0
|
| | |||
| | 0 |
1 |
| | |||
or
M <- matrix(c(0, 0, 0, 1), 2)
Projecting onto the
x
-axis:
| | 1 |
0
|
| | |||
| | 0 |
0 |
| | |||
or
M <- matrix(c(1, 0, 0, 0), 2)
Tilting the coordinates horizontally or vertically. Shearing vertically by 10\
| | 1 |
0 |
| | |||
| | 0.1 |
1 |
| | |||
or M <- matrix(c(1, 0.1, 0, 1), 2)
Shearing horizontally by 200\
| | 1 |
2 |
| | |||
| | 0 |
1 |
| | |||
or M <- matrix(c(1, 0, 2, 1), 2)
A rotation performs a motion around a fixed point, typically the origin the coordinate system. To rotate the coordinates by 90 degrees counter-clockwise:
| | 0 |
-1 |
| | |||
| | 1
|
0 |
| | |||
or M <- matrix(c(0, 1, -1, 0), 2)
For a rotation around any angle :
| | |
|
| | |||
| | |
|
| | |||
or M <- matrix(c(cos(theta), sin(theta), -sin(theta), cos(theta)), 2)
with 'theta
' defined in radians.
df <- data.frame(x = c(0, 1, 1, 0), y = c(0, 0, 1, 1)) ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(angle = 30)) # Custom transformation matrices # Rotation theta <- -30 * pi / 180 rot <- matrix(c(cos(theta), sin(theta), -sin(theta), cos(theta)), 2) # Shear shear <- matrix(c(1, 0, 1, 1), 2) # Shear and then rotate M <- rot %*% shear ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(M = M)) # Alternative shear and then rotate ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(shear = c(0, 1), angle = 30)) # Rotate and then shear M <- shear %*% rot ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(M = M))
df <- data.frame(x = c(0, 1, 1, 0), y = c(0, 0, 1, 1)) ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(angle = 30)) # Custom transformation matrices # Rotation theta <- -30 * pi / 180 rot <- matrix(c(cos(theta), sin(theta), -sin(theta), cos(theta)), 2) # Shear shear <- matrix(c(1, 0, 1, 1), 2) # Shear and then rotate M <- rot %*% shear ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(M = M)) # Alternative shear and then rotate ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(shear = c(0, 1), angle = 30)) # Rotate and then shear M <- shear %*% rot ggplot(df, aes(x, y)) + geom_polygon(position = position_lineartrans(M = M))
When discrete data has some inherent hierarchy to the relationship between discrete categories, you can display a dendrogram instead of a tick axis.
scale_x_dendrogram( ..., hclust = waiver(), expand = waiver(), guide = waiver(), position = "bottom" ) scale_y_dendrogram( ..., hclust = waiver(), expand = waiver(), guide = waiver(), position = "left" )
scale_x_dendrogram( ..., hclust = waiver(), expand = waiver(), guide = waiver(), position = "bottom" ) scale_y_dendrogram( ..., hclust = waiver(), expand = waiver(), guide = waiver(), position = "left" )
... |
Arguments passed on to
|
hclust |
An object of the type produced by the
|
expand |
For position scales, a vector of range expansion constants used to add some
padding around the data to ensure that they are placed some distance
away from the axes. Use the convenience function |
guide |
A function used to create a guide or its name. See
|
position |
For position scales, The position of the axis.
|
The dendrogram type of scale does two things, first it reorders the
values along the relevant direction such that they follow the order
captured in the hclust
argument. Secondly, it draws the dendrogram
at the axis. The dendrogram visuals inherit from the ticks theme elements,
so defining a linetype for the tick marks sets the linetype for the
dendrogram.
A ScaleDendrogram ggproto object.
# Hierarchically cluster USArrests yclus <- hclust(dist(USArrests), "ave") xclus <- hclust(dist(t(USArrests)), "ave") # Melting USArrests df <- data.frame( State = rownames(USArrests)[row(USArrests)], variable = colnames(USArrests)[col(USArrests)], value = unname(do.call(c, USArrests)) ) # Supply the clustering to the scales ggplot(df, aes(variable, State, fill = value)) + geom_raster() + scale_y_dendrogram(hclust = yclus) + scale_x_dendrogram(hclust = xclus)
# Hierarchically cluster USArrests yclus <- hclust(dist(USArrests), "ave") xclus <- hclust(dist(t(USArrests)), "ave") # Melting USArrests df <- data.frame( State = rownames(USArrests)[row(USArrests)], variable = colnames(USArrests)[col(USArrests)], value = unname(do.call(c, USArrests)) ) # Supply the clustering to the scales ggplot(df, aes(variable, State, fill = value)) + geom_raster() + scale_y_dendrogram(hclust = yclus) + scale_x_dendrogram(hclust = xclus)
This function adds position scales (x and y) of individual panels. These can be used to fine-tune limits, breaks and other scale parameters for individual panels, provided the facet allows free scales.
scale_x_facet(expr, ..., type = "continuous") scale_y_facet(expr, ..., type = "continuous")
scale_x_facet(expr, ..., type = "continuous") scale_y_facet(expr, ..., type = "continuous")
expr |
An |
... |
Other arguments passed to the scale. |
type |
A |
These scale functions work through the mechanism of the
facetted_pos_scales()
function, and the same limitations apply: scale
transformations are applied after stat
transformations, and the oob
argument of scales is ignored.
For the expr
argument, the expression will be evaluated in the context
of the plot's layout. This is an internal data.frame
structure that
isn't normally exposed, so it requires some extra knowledge. For most
facets, the layout describes the panels, with one panel per row. It
typically has COL
, ROW
and PANEL
columns that keep track of what
panel goes where in a grid of cells. In addition, it contains the
facetting variables provided to the facets
or rows
and cols
arguments
of the facets. For example, if we have a plot facetted on the var
variable with the levels A
, B
and C
, as 1 row and 3 columns, we might
target the second B
panel with any of these expressions: var == "B"
,
PANEL == 2
or COL == 2
. We can inspect the layout structure by using
ggplot_build(p)$layout$layout
, wherein p
is a plot.
When using multiple scale_(x/y)_facet()
, the expr
argument can target
the same panels. In such case, the scales added to the plot first overrule
the scales that were added later.
A scale_facet
object that can be added to a plot.
The facetted_pos_scales()
function.
# A standard plot with continuous scales p <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + facet_wrap(~ cyl, scales = "free") # Adding a scale for a value for a facetting variable p + scale_x_facet(cyl == 8, limits = c(200, 600)) # Adding a scale by position in the layout p + scale_x_facet(COL == 3, limits = c(200, 600)) # Setting the default scale and making an exception for one panel p + scale_y_continuous(limits = c(0, 40)) + scale_y_facet(PANEL == 1, limits = c(10, 50)) # Using multiple panel-specific scales p + scale_y_facet(PANEL == 1, limits = c(10, 50)) + scale_y_facet(cyl == 6, breaks = scales::breaks_width(0.5)) # When multiple scales target the same panel, the scale added first gets # priority over scales added later. p + scale_y_facet(COL == 2, limits = c(10, 40)) + scale_y_facet(cyl %in% c(4, 6), breaks = scales::breaks_width(1)) # A standard plot with discrete x scales p <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot() + facet_wrap(~ vs, scales = "free") # Expanding limits to show every level p + scale_x_facet(vs == 1, limits = factor(c(4, 6, 8)), type = "discrete") # Shrinking limits to hide a level p + scale_x_facet(vs == 0, limits = factor(c(4, 6)), type = "discrete")
# A standard plot with continuous scales p <- ggplot(mtcars, aes(disp, mpg)) + geom_point() + facet_wrap(~ cyl, scales = "free") # Adding a scale for a value for a facetting variable p + scale_x_facet(cyl == 8, limits = c(200, 600)) # Adding a scale by position in the layout p + scale_x_facet(COL == 3, limits = c(200, 600)) # Setting the default scale and making an exception for one panel p + scale_y_continuous(limits = c(0, 40)) + scale_y_facet(PANEL == 1, limits = c(10, 50)) # Using multiple panel-specific scales p + scale_y_facet(PANEL == 1, limits = c(10, 50)) + scale_y_facet(cyl == 6, breaks = scales::breaks_width(0.5)) # When multiple scales target the same panel, the scale added first gets # priority over scales added later. p + scale_y_facet(COL == 2, limits = c(10, 40)) + scale_y_facet(cyl %in% c(4, 6), breaks = scales::breaks_width(1)) # A standard plot with discrete x scales p <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot() + facet_wrap(~ vs, scales = "free") # Expanding limits to show every level p + scale_x_facet(vs == 1, limits = factor(c(4, 6, 8)), type = "discrete") # Shrinking limits to hide a level p + scale_x_facet(vs == 0, limits = factor(c(4, 6)), type = "discrete")
Maps multiple aesthetics to multiple colour fill gradient
scales. It takes in listed arguments for each aesthetic and disseminates
these to ggplot2::continuous_scale()
.
scale_fill_multi( ..., colours, values = NULL, na.value = "transparent", guide = "colourbar", aesthetics = "fill", colors ) scale_colour_multi( ..., colours, values = NULL, na.value = "transparent", guide = "colourbar", aesthetics = "colour", colors )
scale_fill_multi( ..., colours, values = NULL, na.value = "transparent", guide = "colourbar", aesthetics = "fill", colors ) scale_colour_multi( ..., colours, values = NULL, na.value = "transparent", guide = "colourbar", aesthetics = "colour", colors )
... , colours , values , na.value , guide , colors
|
listed arguments in
|
aesthetics |
a |
This function should only be called after all layers that this function affects are added to the plot.
The list elements of the listed arguments are assumed to follow the
aesthetics
order, i.e. the nth list element belongs to the nth
aesthetic. When there are more list elements than n aesthetics, only the
first nth list elements are taken. When there are more aesthetics
than list elements, the first list element is used for the remaining
aesthethics.
In contrast to other scale_*_continous
-family functions, the
guide
argument is interpreted before adding it to the plot instead
of at the time of plot building. This behaviour ensures that the
available_aes
argument of the guides are set correctly, but may
interfere with the ggplot2::guides()
function.
A nested list-like structure of the class MultiScale
.
# Setup dummy data df <- rbind(data.frame(x = 1:3, y = 1, v = NA, w = 1:3, z = NA), data.frame(x = 1:3, y = 2, v = 1:3, w = NA, z = NA), data.frame(x = 1:3, y = 3, v = NA, w = NA, z = 1:3)) ggplot(df, aes(x, y)) + geom_raster(aes(fill1 = v)) + geom_raster(aes(fill2 = w)) + geom_raster(aes(fill3 = z)) + scale_fill_multi(aesthetics = c("fill1", "fill2", "fill3"), colours = list(c("white", "red"), c("black", "blue"), c("grey50", "green")))
# Setup dummy data df <- rbind(data.frame(x = 1:3, y = 1, v = NA, w = 1:3, z = NA), data.frame(x = 1:3, y = 2, v = 1:3, w = NA, z = NA), data.frame(x = 1:3, y = 3, v = NA, w = NA, z = 1:3)) ggplot(df, aes(x, y)) + geom_raster(aes(fill1 = v)) + geom_raster(aes(fill2 = w)) + geom_raster(aes(fill3 = z)) + scale_fill_multi(aesthetics = c("fill1", "fill2", "fill3"), colours = list(c("white", "red"), c("black", "blue"), c("grey50", "green")))
This function should only be called after all layers that the non-standard aesthetic scales affects have been added to the plot.
Inside a layer, the non-standard aesthetic should be part of the call to
aes
mapping.
May return a warning that the plot is ignoring unknown aesthetics.
scale_listed(scalelist, replaces = NULL)
scale_listed(scalelist, replaces = NULL)
scalelist |
A |
replaces |
A |
Distributes a list of non-standard aesthetics scales to the plot, substituting geom and scale settings as necessary to display the non-standard aesthetics. Useful for mapping different geoms to different scales for example.
A list
of which the elements are of the class
MultiScale
.
# Annotation of heatmap iriscor <- cor(t(iris[, 1:4])) df <- data.frame( x = as.vector(row(iriscor)), y = as.vector(col(iriscor)), value = as.vector(iriscor) ) annotation <- data.frame( z = seq_len(nrow(iris)), Species = iris$Species, Leaves = ifelse(iris$Species == "setosa", "Short", "Long") ) ggplot(df, aes(x, y)) + geom_raster(aes(fill = value)) + geom_tile(data = annotation, aes(x = z, y = -5, spec = Species), height = 5) + geom_tile(data = annotation, aes(y = z, x = -5, leav = Leaves), width = 5) + scale_listed( list(scale_fill_brewer(palette = "Set1", aesthetics = "spec"), scale_fill_brewer(palette = "Dark2", aesthetics = "leav")), replaces = c("fill", "fill") )
# Annotation of heatmap iriscor <- cor(t(iris[, 1:4])) df <- data.frame( x = as.vector(row(iriscor)), y = as.vector(col(iriscor)), value = as.vector(iriscor) ) annotation <- data.frame( z = seq_len(nrow(iris)), Species = iris$Species, Leaves = ifelse(iris$Species == "setosa", "Short", "Long") ) ggplot(df, aes(x, y)) + geom_raster(aes(fill = value)) + geom_tile(data = annotation, aes(x = z, y = -5, spec = Species), height = 5) + geom_tile(data = annotation, aes(y = z, x = -5, leav = Leaves), width = 5) + scale_listed( list(scale_fill_brewer(palette = "Set1", aesthetics = "spec"), scale_fill_brewer(palette = "Dark2", aesthetics = "leav")), replaces = c("fill", "fill") )
scale_x_manual()
and scale_y_manual()
are hybrid discrete and continuous
position scales for the x
and y
aesthetics. These accept input like
discrete scales, but may map these discrete
values to continuous values that needn't be equally spaced.
scale_x_manual(values, c_limits = NULL, position = "bottom", ...) scale_y_manual(values, c_limits = NULL, position = "left", ...)
scale_x_manual(values, c_limits = NULL, position = "bottom", ...) scale_y_manual(values, c_limits = NULL, position = "left", ...)
values |
A |
c_limits |
Either |
position |
For position scales, The position of the axis.
|
... |
Arguments passed on to
|
Many thanks to Constantin Ahlmann-Eltze for discussion and suggesting the adoption of this functionality in ggh4x.
A <ScaleManualPosition>
object that can be added to a plot.
There currently is a known bug wherein a c_limits
cannot be applied
correctly when that range is within the range of the discrete limits.
# A boxplot with interactions p <- ggplot(mpg, aes(interaction(year, cyl), displ)) + geom_boxplot() # Manually setting positions p + scale_x_manual(values = c(1, 2, 4, 6, 7, 9, 10)) # Using a function to separate grouped labels p + scale_x_manual(values = sep_discrete()) # Expanding the continuous limits p + scale_x_manual(values = sep_discrete(), c_limits = c(NA, 15)) # Together with grouped axis p + scale_x_manual(values = sep_discrete(), guide = guide_axis_nested())
# A boxplot with interactions p <- ggplot(mpg, aes(interaction(year, cyl), displ)) + geom_boxplot() # Manually setting positions p + scale_x_manual(values = c(1, 2, 4, 6, 7, 9, 10)) # Using a function to separate grouped labels p + scale_x_manual(values = sep_discrete()) # Expanding the continuous limits p + scale_x_manual(values = sep_discrete(), c_limits = c(NA, 15)) # Together with grouped axis p + scale_x_manual(values = sep_discrete(), guide = guide_axis_nested())
This is a function factory that provides a function to split grouped discrete labels into numerical positions.
sep_discrete(sep = ".", inv = FALSE)
sep_discrete(sep = ".", inv = FALSE)
sep |
A |
inv |
A |
A function
that accepts character
input and returns
numeric
output.
# Here, 'bar.qux' belongs to the second group, so has +1 value sep_discrete()(c("foo.bar", "bar.bar", "bar.qux")) # Now, the values are grouped by the groups before the separator sep_discrete(inv = TRUE)(c("foo.bar", "bar.bar", "bar.qux"))
# Here, 'bar.qux' belongs to the second group, so has +1 value sep_discrete()(c("foo.bar", "bar.bar", "bar.qux")) # Now, the values are grouped by the groups before the separator sep_discrete(inv = TRUE)(c("foo.bar", "bar.bar", "bar.qux"))
This makes a ribbon that is filled depending on whether the max
is
higher than min
. This can be useful for displaying differences
between two series.
stat_difference( mapping = NULL, data = NULL, geom = "ribbon", position = "identity", ..., levels = c("+", "-"), na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )
stat_difference( mapping = NULL, data = NULL, geom = "ribbon", position = "identity", ..., levels = c("+", "-"), na.rm = FALSE, orientation = NA, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
Use to override the default connection between
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
levels |
A |
na.rm |
If |
orientation |
The orientation of the layer. The default ( |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
The stat may reorder the group
aesthetic to accommodate two
different fills for the signs of differences. The stat takes care to
interpolate a series whenever a crossover between max
and min
series
happens. This makes the ribbon not look stumpy at these crossovers.
A Layer
object that can be added to a plot.
geom_ribbon()
understands the following aesthetics (required aesthetics are in bold):
Learn more about setting these aesthetics in vignette("ggplot2-specs")
.
sign
A factor
with the levels
attribute set to the levels
argument.
When there is a run of more than two 0-difference values, the inner values will be ignored.
set.seed(2021) df <- data.frame( x = 1:100, y = cumsum(rnorm(100)), z = cumsum(rnorm(100)) ) ggplot(df, aes(x = x)) + stat_difference(aes(ymin = y, ymax = z), alpha = 0.3) + geom_line(aes(y = y, colour = "min")) + geom_line(aes(y = z, colour = "max"))
set.seed(2021) df <- data.frame( x = 1:100, y = cumsum(rnorm(100)), z = cumsum(rnorm(100)) ) ggplot(df, aes(x = x)) + stat_difference(aes(ymin = y, ymax = z), alpha = 0.3) + geom_line(aes(y = y, colour = "min")) + geom_line(aes(y = z, colour = "max"))
The function xy stat applies a function to the x- and y-coordinates of a
layers positions by group. The stat_centroid()
and
stat_midpoint()
functions are convenience wrappers for calculating
centroids and midpoints. stat_funxy()
by default leaves the data
as-is, but can be supplied functions and arguments.
stat_funxy( mapping = NULL, data = NULL, geom = "point", position = "identity", ..., funx = force, funy = force, argx = list(), argy = list(), crop_other = TRUE, show.legend = NA, inherit.aes = TRUE ) stat_centroid( ..., funx = mean, funy = mean, argx = list(na.rm = TRUE), argy = list(na.rm = TRUE) ) stat_midpoint(..., argx = list(na.rm = TRUE), argy = list(na.rm = TRUE))
stat_funxy( mapping = NULL, data = NULL, geom = "point", position = "identity", ..., funx = force, funy = force, argx = list(), argy = list(), crop_other = TRUE, show.legend = NA, inherit.aes = TRUE ) stat_centroid( ..., funx = mean, funy = mean, argx = list(na.rm = TRUE), argy = list(na.rm = TRUE) ) stat_midpoint(..., argx = list(na.rm = TRUE), argy = list(na.rm = TRUE))
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
The geometric object to use to display the data for this layer.
When using a
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
funx , funy
|
A |
argx , argy
|
A named |
crop_other |
A |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
This statistic only makes a minimal attempt at ensuring that the results from calling both functions are of equal length. Results of length 1 are recycled to match the longest length result.
A StatFunxy
ggproto object, that can be added to a plot.
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) # Labelling group midpoints p + geom_point() + stat_midpoint(aes(label = Species, group = Species), geom = "text", colour = "black") # Drawing segments to centroids p + geom_point() + stat_centroid(aes(xend = Sepal.Width, yend = Sepal.Length), geom = "segment", crop_other = FALSE) # Drawing intervals ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) + geom_point() + stat_funxy(geom = "path", funx = median, funy = quantile, argy = list(probs = c(0.1, 0.9)))
p <- ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) # Labelling group midpoints p + geom_point() + stat_midpoint(aes(label = Species, group = Species), geom = "text", colour = "black") # Drawing segments to centroids p + geom_point() + stat_centroid(aes(xend = Sepal.Width, yend = Sepal.Length), geom = "segment", crop_other = FALSE) # Drawing intervals ggplot(iris, aes(Sepal.Width, Sepal.Length, colour = Species)) + geom_point() + stat_funxy(geom = "path", funx = median, funy = quantile, argy = list(probs = c(0.1, 0.9)))
Run length encoding takes a vector of values and calculates the lengths of consecutive repeated values.
stat_rle( mapping = NULL, data = NULL, geom = "rect", position = "identity", ..., align = "none", na.rm = FALSE, orientation = "x", show.legend = NA, inherit.aes = TRUE )
stat_rle( mapping = NULL, data = NULL, geom = "rect", position = "identity", ..., align = "none", na.rm = FALSE, orientation = "x", show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
Use to override the default connection between
|
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
align |
A
|
na.rm |
If |
orientation |
The orientation of the layer. The default ( |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
The data is first ordered on the x
aesthetic before run lengths are
calculated for the label
aesthetic. In contrast to base::rle()
, NA
s
are considered equivalent values, not different values.
A ggplot2
layer
stat_rle()
understands the following
aesthetics (required aesthetics are in bold)
x
label
group
The x
values at the start of every run.
The x
values at the end of every run.
The index where a run starts.
The index where a run ends.
The index of a run.
The length of a run.
The value associated with a run.
df <- data.frame( x = seq(0, 10, length.out = 100), y = sin(seq(0, 10, length.out = 100)*2) ) # Label every run of increasing values ggplot(df) + stat_rle(aes(x, label = diff(c(0, y)) > 0), align = "end") + geom_point(aes(x, y)) # Label every run above some threshold ggplot(df) + stat_rle(aes(x, label = y > 0), align = "center") + geom_point(aes(x, y)) # Categorising runs, more complicated usage ggplot(df) + stat_rle(aes(stage(x, after_stat = run_id), after_stat(runlength), label = cut(y, c(-1, -0.6, 0.6, 1)), fill = after_stat(runvalue)), geom = "col")
df <- data.frame( x = seq(0, 10, length.out = 100), y = sin(seq(0, 10, length.out = 100)*2) ) # Label every run of increasing values ggplot(df) + stat_rle(aes(x, label = diff(c(0, y)) > 0), align = "end") + geom_point(aes(x, y)) # Label every run above some threshold ggplot(df) + stat_rle(aes(x, label = y > 0), align = "center") + geom_point(aes(x, y)) # Categorising runs, more complicated usage ggplot(df) + stat_rle(aes(stage(x, after_stat = run_id), after_stat(runlength), label = cut(y, c(-1, -0.6, 0.6, 1)), fill = after_stat(runvalue)), geom = "col")
A rolling kernel moves along one of the axes and assigns weights to datapoints depending on the distance to the kernel's location. It then calculates a weighted average on the y-values of the datapoints, creating a trendline. In contrast to (weighted) rolling averages, the interval between datapoints do not need to be constant.
stat_rollingkernel( mapping = NULL, data = NULL, geom = "line", position = "identity", ..., bw = "nrd", kernel = "gaussian", n = 256, expand = 0.1, na.rm = FALSE, orientation = "x", show.legend = NA, inherit.aes = TRUE )
stat_rollingkernel( mapping = NULL, data = NULL, geom = "line", position = "identity", ..., bw = "nrd", kernel = "gaussian", n = 256, expand = 0.1, na.rm = FALSE, orientation = "x", show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
Use to override the default geom ( |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
bw |
A bandwidth, which can be one of the following:
|
kernel |
One of the following:
|
n |
An |
expand |
A |
na.rm |
If |
orientation |
A |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
A Layer ggproto object.
stat_rollingkernel()
understands the following
aesthetics (required aesthetics are in bold)
x
y
group
x
A sequence of ordered x positions.
y
The weighted value of the rolling kernel.
weight
The sum of weight strengths at a position.
scaled
The fraction of weight strengths at a position. This is
the same as weight / sum(weight)
by group.
ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + stat_rollingkernel() # The (scaled) weights can be used to emphasise data-dense areas ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + stat_rollingkernel(aes(alpha = after_stat(scaled)))
ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + stat_rollingkernel() # The (scaled) weights can be used to emphasise data-dense areas ggplot(mpg, aes(displ, hwy, colour = class)) + geom_point() + stat_rollingkernel(aes(alpha = after_stat(scaled)))
Estimates the parameters of a given distribution and evaluates the probability density function with these parameters. This can be useful for comparing histograms or kernel density estimates against a theoretical distribution.
stat_theodensity( mapping = NULL, data = NULL, geom = "line", position = "identity", ..., distri = "norm", n = 512, fix.arg = NULL, start.arg = NULL, na.rm = TRUE, show.legend = NA, inherit.aes = TRUE )
stat_theodensity( mapping = NULL, data = NULL, geom = "line", position = "identity", ..., distri = "norm", n = 512, fix.arg = NULL, start.arg = NULL, na.rm = TRUE, show.legend = NA, inherit.aes = TRUE )
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
Use to override the default geom for |
position |
A position adjustment to use on the data for this layer. This
can be used in various ways, including to prevent overplotting and
improving the display. The
|
... |
Other arguments passed on to
|
distri |
A |
n |
An |
fix.arg |
An optional named list giving values of fixed parameters of the named distribution. Parameters with fixed value are not estimated by maximum likelihood procedures. |
start.arg |
A named list giving initial values of parameters for the named distribution. This argument may be omitted (default) for some distributions for which reasonable starting values are computed. |
na.rm |
If |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
Valid distri
arguments are the names of distributions for
which there exists a density function. The names should be given without a
prefix (typically 'd', 'r', 'q' and 'r'). For example: "norm"
for
the normal distribution and "nbinom"
for the negative binomial
distribution. Take a look at distributions()
in the
stats package for an overview.
There are a couple of distribution for which there exist no reasonable
starting values, such as the Student t-distribution and the F-distribution.
In these cases, it would probably be wise to provide reasonable starting
values as a named list to the start.arg
argument. When estimating a
binomial distribution, it would be best to supply the size
to the
fix.arg
argument.
By default, the y values are such that the integral of the distribution is
1, which scales well with the defaults of kernel density estimates. When
comparing distributions with absolute count histograms, a sensible choice
for aesthetic mapping would be aes(y = stat(count) * binwidth)
,
wherein binwidth
is matched with the bin width of the histogram.
For discrete distributions, the input data are expected to be integers, or doubles that can be divided by 1 without remainders.
Parameters are estimated using the
fitdistrplus::fitdist()
function in the
fitdistrplus package using maximum likelihood estimation.
Hypergeometric and multinomial distributions from the stats package
are not supported.
A Layer ggproto object.
probability density
density * number of observations - useful for comparing to histograms
density scaled to a maximum of 1
stats::Distributions()
fitdistrplus::fitdist()
ggplot2::geom_density()
ggplot2::geom_histogram()
# A mixture of normal distributions where the standard deviation is # inverse gamma distributed resembles a cauchy distribution. x <- rnorm(2000, 10, 1/rgamma(2000, 2, 0.5)) df <- data.frame(x = x) ggplot(df, aes(x)) + geom_histogram(binwidth = 0.1, alpha = 0.3, position = "identity") + stat_theodensity(aes(y = stat(count) * 0.1, colour = "Normal"), distri = "norm", geom = "line") + stat_theodensity(aes(y = stat(count) * 0.1, colour = "Cauchy"), distri = "cauchy", geom = "line") + coord_cartesian(xlim = c(5, 15)) # A negative binomial can be understood as a Poisson-gamma mixture df <- data.frame(x = c(rpois(500, 25), rpois(500, rgamma(500, 5, 0.2))), cat = rep(c("Poisson", "Poisson-gamma"), each = 500)) ggplot(df, aes(x)) + geom_histogram(binwidth = 1, aes(fill = cat), alpha = 0.3, position = "identity") + stat_theodensity(aes(y = stat(count), colour = cat), distri = "nbinom", geom = "step", position = position_nudge(x = -0.5)) + stat_summary(aes(y = x, colour = cat, x = 1), fun.data = function(x){data.frame(xintercept = mean(x))}, geom = "vline")
# A mixture of normal distributions where the standard deviation is # inverse gamma distributed resembles a cauchy distribution. x <- rnorm(2000, 10, 1/rgamma(2000, 2, 0.5)) df <- data.frame(x = x) ggplot(df, aes(x)) + geom_histogram(binwidth = 0.1, alpha = 0.3, position = "identity") + stat_theodensity(aes(y = stat(count) * 0.1, colour = "Normal"), distri = "norm", geom = "line") + stat_theodensity(aes(y = stat(count) * 0.1, colour = "Cauchy"), distri = "cauchy", geom = "line") + coord_cartesian(xlim = c(5, 15)) # A negative binomial can be understood as a Poisson-gamma mixture df <- data.frame(x = c(rpois(500, 25), rpois(500, rgamma(500, 5, 0.2))), cat = rep(c("Poisson", "Poisson-gamma"), each = 500)) ggplot(df, aes(x)) + geom_histogram(binwidth = 1, aes(fill = cat), alpha = 0.3, position = "identity") + stat_theodensity(aes(y = stat(count), colour = cat), distri = "nbinom", geom = "step", position = position_nudge(x = -0.5)) + stat_summary(aes(y = x, colour = cat, x = 1), fun.data = function(x){data.frame(xintercept = mean(x))}, geom = "vline")
This strip style groups strips on the same layer that share a label. It is
the default strip for facet_nested()
and
facet_nested_wrap()
.
strip_nested( clip = "inherit", size = "constant", bleed = FALSE, text_x = NULL, text_y = NULL, background_x = NULL, background_y = NULL, by_layer_x = FALSE, by_layer_y = FALSE )
strip_nested( clip = "inherit", size = "constant", bleed = FALSE, text_x = NULL, text_y = NULL, background_x = NULL, background_y = NULL, by_layer_x = FALSE, by_layer_y = FALSE )
clip |
A |
size |
A |
bleed |
A |
text_x , text_y
|
A |
background_x , background_y
|
A |
by_layer_x , by_layer_y
|
A |
The display order is always such that the outermost variable is placed the furthest away from the panels. Strips are automatically grouped when they span a nested variable.
The bleed
argument controls whether lower-layer strips are allowed
to be merged when higher-layer strips are different, i.e. they can bleed
over hierarchies. Suppose the strip_vanilla()
behaviour would be the
following for strips:
[_1_][_2_][_2_]
[_3_][_3_][_4_]
In such case, the default bleed = FALSE
argument would result in the
following:
[_1_][___2____]
[_3_][_3_][_4_]
Whereas bleed = TRUE
would allow the following:
[_1_][___2____]
[___3____][_4_]
A StripNested
ggproto object that can be given as an argument to
facets in ggh4x.
Other strips:
strip_split()
,
strip_themed()
,
strip_vanilla()
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Combine the strips p + facet_wrap2(vars(cyl, drv), strip = strip_nested()) # The facet_nested and facet_nested_wrap functions have nested strips # automatically p + facet_nested_wrap(vars(cyl, drv)) # Changing the bleed argument merges the "f" labels in the top-right p + facet_wrap2(vars(cyl, drv), strip = strip_nested(bleed = TRUE))
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Combine the strips p + facet_wrap2(vars(cyl, drv), strip = strip_nested()) # The facet_nested and facet_nested_wrap functions have nested strips # automatically p + facet_nested_wrap(vars(cyl, drv)) # Changing the bleed argument merges the "f" labels in the top-right p + facet_wrap2(vars(cyl, drv), strip = strip_nested(bleed = TRUE))
This strip style allows a greater control over where a strip is placed relative to the panel. Different facetting variables are allowed to be placed on different sides.
strip_split( position = c("top", "left"), clip = "inherit", size = "constant", bleed = FALSE, text_x = NULL, text_y = NULL, background_x = NULL, background_y = NULL, by_layer_x = FALSE, by_layer_y = FALSE )
strip_split( position = c("top", "left"), clip = "inherit", size = "constant", bleed = FALSE, text_x = NULL, text_y = NULL, background_x = NULL, background_y = NULL, by_layer_x = FALSE, by_layer_y = FALSE )
position |
A |
clip |
A |
size |
A |
bleed |
A |
text_x , text_y
|
A |
background_x , background_y
|
A |
by_layer_x , by_layer_y
|
A |
Using this style of strip completely overrules the strip.position
and switch
arguments.
A StripSplit
ggproto object that can be given as an argument to
facets in ggh4x.
Other strips:
strip_nested()
,
strip_themed()
,
strip_vanilla()
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # --- Wrap examples ------ # Defaults to 1st (cyl) at top, 2nd (drv) on left p + facet_wrap2(vars(cyl, drv), strip = strip_split()) # Change cyl to left, drv to bottom p + facet_wrap2(vars(cyl, drv), strip = strip_split(c("left", "bottom"))) # --- Grid examples ----- # Display both strips levels on the left p + facet_grid2(vars(drv), vars(cyl), strip = strip_split(c("left", "left"))) # Separate the strips again p + facet_grid2(vars(cyl, year), strip = strip_split(c("bottom", "left"))) # Using a dummy variable as a title strip p + facet_grid2(vars(cyl, "year", year), strip = strip_split(c("bottom", "left", "left")))
# A standard plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # --- Wrap examples ------ # Defaults to 1st (cyl) at top, 2nd (drv) on left p + facet_wrap2(vars(cyl, drv), strip = strip_split()) # Change cyl to left, drv to bottom p + facet_wrap2(vars(cyl, drv), strip = strip_split(c("left", "bottom"))) # --- Grid examples ----- # Display both strips levels on the left p + facet_grid2(vars(drv), vars(cyl), strip = strip_split(c("left", "left"))) # Separate the strips again p + facet_grid2(vars(cyl, year), strip = strip_split(c("bottom", "left"))) # Using a dummy variable as a title strip p + facet_grid2(vars(cyl, "year", year), strip = strip_split(c("bottom", "left", "left")))
A style of strips with individually themed strips.
strip_themed( clip = "inherit", size = "constant", text_x = NULL, text_y = NULL, background_x = NULL, background_y = NULL, by_layer_x = FALSE, by_layer_y = FALSE )
strip_themed( clip = "inherit", size = "constant", text_x = NULL, text_y = NULL, background_x = NULL, background_y = NULL, by_layer_x = FALSE, by_layer_y = FALSE )
clip |
A |
size |
A |
text_x , text_y
|
A |
background_x , background_y
|
A |
by_layer_x , by_layer_y
|
A |
With respect to the text_*
and background_*
arguments, they can
be a list with (a mix of) the following objects:
NULL
indicates that the global plot theme applies.
element_blank()
omits drawing the background or text.
An element
class object inheriting from the element_text
or
element_rect
classes.
For constructing homogeneous lists of elements, the
elem_list_text()
and
elem_list_rect()
are provided for convenience.
A StripThemed
ggproto object that can be given as an argument to
facets in ggh4x.
Other strips:
strip_nested()
,
strip_split()
,
strip_vanilla()
# Some simple plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Set some theming options, we can use `element_blank()` backgrounds <- list(element_blank(), element_rect(fill = "dodgerblue")) # Or we could use `NULL` to use the global theme texts <- list(element_text(colour = "red"), NULL, element_text(face = "bold")) # Elements are repeated until the fit the number of facets p + facet_wrap2( vars(drv, year), strip = strip_themed( background_x = backgrounds, text_x = texts ) ) # Except when applied to each layer instead of every strip p + facet_wrap2( vars(drv, year), strip = strip_themed( background_x = backgrounds, text_x = texts, by_layer_x = TRUE ) ) # To conveniently distribute arguments over a list of the same elements, # you can use the following wrappers: p + facet_wrap2( vars(drv, year), strip = strip_themed( text_x = elem_list_text(colour = c("blue", "red")), background_x = elem_list_rect(fill = c("white", "grey80")), by_layer_x = TRUE ) )
# Some simple plot p <- ggplot(mpg, aes(displ, hwy)) + geom_point() # Set some theming options, we can use `element_blank()` backgrounds <- list(element_blank(), element_rect(fill = "dodgerblue")) # Or we could use `NULL` to use the global theme texts <- list(element_text(colour = "red"), NULL, element_text(face = "bold")) # Elements are repeated until the fit the number of facets p + facet_wrap2( vars(drv, year), strip = strip_themed( background_x = backgrounds, text_x = texts ) ) # Except when applied to each layer instead of every strip p + facet_wrap2( vars(drv, year), strip = strip_themed( background_x = backgrounds, text_x = texts, by_layer_x = TRUE ) ) # To conveniently distribute arguments over a list of the same elements, # you can use the following wrappers: p + facet_wrap2( vars(drv, year), strip = strip_themed( text_x = elem_list_text(colour = c("blue", "red")), background_x = elem_list_rect(fill = c("white", "grey80")), by_layer_x = TRUE ) )
Strips with the style of vanilla ggplot2.
strip_vanilla(clip = "inherit", size = "constant")
strip_vanilla(clip = "inherit", size = "constant")
clip |
A |
size |
A |
A Strip
ggproto object that can be used ggh4x facets.
Other strips:
strip_nested()
,
strip_split()
,
strip_themed()
# Some dummy data with a long string df <- data.frame( short = "X", long = "A very long string that takes up a lot of space", value = 1 ) # Simple plot p <- ggplot(df, aes(value, value)) + geom_point() + theme(strip.text.y.right = element_text(angle = 0)) # Short titles take up as much space as long titles p + facet_grid2( vars(short, long), strip = strip_vanilla(size = "constant") ) # Short titles take up less space p + facet_grid2( vars(short, long), strip = strip_vanilla(size = "variable") )
# Some dummy data with a long string df <- data.frame( short = "X", long = "A very long string that takes up a lot of space", value = 1 ) # Simple plot p <- ggplot(df, aes(value, value)) + geom_point() + theme(strip.text.y.right = element_text(angle = 0)) # Short titles take up as much space as long titles p + facet_grid2( vars(short, long), strip = strip_vanilla(size = "constant") ) # Short titles take up less space p + facet_grid2( vars(short, long), strip = strip_vanilla(size = "variable") )
Some functions in ggh4x are using extensions to the theme system. These extended theme argument are listed below, along with what elements they are expected to be, and in what function(s) they are used.
ggh4x.facet.nestline |
An |
ggh4x.axis.nestline , ggh4x.axis.nestline.x , ggh4x.axis.nestline.y
|
An
|
ggh4x.axis.nesttext.x , ggh4x.axis.nesttext.y
|
An |
ggh4x.axis.ticks.length.minor |
A |
ggh4x.axis.ticks.length.mini |
A |
Computes a new factor out of combinations of input factors.
weave_factors(..., drop = TRUE, sep = ".", replaceNA = TRUE)
weave_factors(..., drop = TRUE, sep = ".", replaceNA = TRUE)
... |
The vectors |
drop |
A |
sep |
A |
replaceNA |
A |
weave_factors()
broadly resembles interaction(..., lex.order = TRUE)
, with a slightly altered approach to non-factor inputs.
In other words, this function orders the new levels such that the levels of
the first input variable in ...
is given priority over the second
input, the second input has priority over the third, etc.
This function treats non-factor inputs as if their levels were
unique(as.character(x))
, wherein x
represents an input.
A factor
representing combinations of input factors.
f1 <- c("banana", "apple", "apple", "kiwi") f2 <- factor(c(1, 1:3), labels = c("house", "cat", "dog")) # Notice the difference in level ordering between the following: interaction(f1, f2, drop = TRUE, lex.order = TRUE) interaction(f1, f2, drop = TRUE, lex.order = FALSE) weave_factors(f1, f2) # The difference is in how characters are interpreted # The following are equivalent interaction(f1, f2, drop = TRUE, lex.order = TRUE) weave_factors(as.factor(f1), f2)
f1 <- c("banana", "apple", "apple", "kiwi") f2 <- factor(c(1, 1:3), labels = c("house", "cat", "dog")) # Notice the difference in level ordering between the following: interaction(f1, f2, drop = TRUE, lex.order = TRUE) interaction(f1, f2, drop = TRUE, lex.order = FALSE) weave_factors(f1, f2) # The difference is in how characters are interpreted # The following are equivalent interaction(f1, f2, drop = TRUE, lex.order = TRUE) weave_factors(as.factor(f1), f2)