A candlestick summarises the values observed within one instance of a time
granule with four statistics known as 'OHLC': the first value (open), the
largest (high), the smallest (low), and the last (close). These
summary statistics for each granule are drawn as a vertical line spanning
from low to high, overlaid with a rectangle spanning open to close.
The colour and fill of the geometry indicate the change's direction, by
default rising values use green while falling values use red.
Candlesticks are cut on the granule's boundaries, and the width of the
candlestick reflects the length of time in that granule. Granules of uneven
length (e.g. month granules on a day chronon scale via
geom_candlestick(granule = month(1L)) + scale_x_mixtime(time_chronon = day(1L)))
are therefore drawn at uneven widths, each filling its own instance.
geom_candlestick(
mapping = NULL,
data = NULL,
stat = "ohlc",
position = "identity",
...,
granule,
width = 0.9,
lineend = "butt",
linejoin = "mitre",
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE
)
stat_ohlc(
mapping = NULL,
data = NULL,
geom = "candlestick",
position = "identity",
...,
granule,
width = 0.9,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE
)Set of aesthetic mappings created by aes(). If specified and
inherit.aes = TRUE (the default), it is combined with the default mapping
at the top level of the plot. You must supply mapping if there is no plot
mapping.
The data to be displayed in this layer. There are three options:
If NULL, the default, the data is inherited from the plot
data as specified in the call to ggplot().
A data.frame, or other object, will override the plot
data. All objects will be fortified to produce a data frame. See
fortify() for which variables will be created.
A function will be called with a single argument,
the plot data. The return value must be a data.frame, and
will be used as the layer data. A function can be created
from a formula (e.g. ~ head(.x, 10)).
The statistical transformation to use on the data for this layer.
When using a geom_*() function to construct a layer, the stat
argument can be used to override the default coupling between geoms and
stats. The stat argument accepts the following:
A Stat ggproto subclass, for example StatCount.
A string naming the stat. To give the stat as a string, strip the
function name of the stat_ prefix. For example, to use stat_count(),
give the stat as "count".
For more information and other ways to specify the stat, see the layer stat documentation.
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 position argument accepts the following:
The result of calling a position function, such as position_jitter().
This method allows for passing extra arguments to the position.
A string naming the position adjustment. To give the position as a
string, strip the function name of the position_ prefix. For example,
to use position_jitter(), give the position as "jitter".
For more information and other ways to specify the position, see the layer position documentation.
Other arguments passed on to layer()'s params argument. These
arguments broadly fall into one of 4 categories below. Notably, further
arguments to the position argument, or aesthetics that are required
can not be passed through .... Unknown arguments that are not part
of the 4 categories below are ignored.
Static aesthetics that are not mapped to a scale, but are at a fixed
value and apply to the layer as a whole. For example, colour = "red"
or linewidth = 3. The geom's documentation has an Aesthetics
section that lists the available options. The 'required' aesthetics
cannot be passed on to the params. Please note that while passing
unmapped aesthetics as vectors is technically possible, the order and
required length is not guaranteed to be parallel to the input data.
When constructing a layer using
a stat_*() function, the ... argument can be used to pass on
parameters to the geom part of the layer. An example of this is
stat_density(geom = "area", outline.type = "both"). The geom's
documentation lists which parameters it can accept.
Inversely, when constructing a layer using a
geom_*() function, the ... argument can be used to pass on parameters
to the stat part of the layer. An example of this is
geom_area(stat = "density", adjust = 0.5). The stat's documentation
lists which parameters it can accept.
The key_glyph argument of layer() may also be passed on through
.... This can be one of the functions described as
key glyphs, to change the display of the layer in the legend.
The time granule to summarise within, given as:
a duration, e.g. mixtime::days(1L)
a time granule, e.g. mixtime::cal_gregorian$month(1L)
a bare expression, e.g. month(1L), naming a granule of whichever
calendar the time axis uses (see the "Time granules" section below).
There is no default: a candlestick is defined by the granule it summarises, and the granule that suits a series is a property of the analysis rather than of the data.
The width of each candlestick's body, as a proportion of the
granule instance it summarises. Defaults to 0.9, leaving a small gap
between neighbouring candlesticks. A width of 1 makes each body span
its whole granule instance, so that neighbours touch.
Line end style for the high-low line (round, butt, square).
Line join style for the open-close body (round, mitre, bevel).
If FALSE, the default, missing values are removed with
a warning. If TRUE, missing values are silently removed.
The orientation of the layer. The default (NA)
automatically determines the orientation from the aesthetic mapping. In the
rare event that this fails it can be given explicitly by setting orientation
to either "x" or "y". See the Orientation section for more detail.
logical. Should this layer be included in the legends?
NA, the default, includes if any aesthetics are mapped.
FALSE never includes, and TRUE always includes.
It can also be a named logical vector to finely select the aesthetics to
display. To include legend keys for all levels, even
when no data exists, use TRUE. If NA, all levels are shown in legend,
but unobserved levels are omitted.
If FALSE, overrides the default aesthetics,
rather than combining with them. This is most useful for helper functions
that define both data and aesthetics and shouldn't inherit behaviour from
the default plot specification, e.g. annotation_borders().
The geometric object to use to display the data for this layer.
When using a stat_*() function to construct a layer, the geom argument
can be used to override the default coupling between stats and geoms. The
geom argument accepts the following:
A Geom ggproto subclass, for example GeomPoint.
A string naming the geom. To give the geom as a string, strip the
function name of the geom_ prefix. For example, to use geom_point(),
give the geom as "point".
For more information and other ways to specify the geom, see the layer geom documentation.
Each of the four summary statistics is carried by an axis-specific pair of
the positional aesthetics ggplot2::geom_boxplot() uses: [x/y]lower,
[x/y]upper, [x/y]min and [x/y]max. Being ggplot2's own position
aesthetics, the position scales transform and train them, and
ggplot2::flip_data() pairs the two members up, so only the member on the
axis holding the values is ever mapped:
| Statistic | Values on y (time on x) | Values on x (time on y) |
open | lower | xlower |
high | ymax | xmax |
low | ymin | xmin |
close | upper | xupper |
ggplot2 spells the y member of the lower/upper pair without its y
prefix (lower, not ylower), as ggplot2::geom_boxplot() does.
stat_ohlc() computes all four from the y aesthetic (the values to
summarise), so they are only mapped directly to draw values that are already
summarised. If these OHLC values are provided as plot aesthetics and
stat_ohlc() is used with a coarser granule, they will be incorporated into
the new summary at the coarser granularity (e.g. daily open-high-low-close
prices can be drawn as weekly or monthly candlesticks)
These are calculated by stat_ohlc(), and available to
ggplot2::after_stat():
open, high, low, closeThe four summary statistics, also placed on the positional aesthetics above.
directionWhether the candlestick closed above ("rising"),
below ("falling"), or level with ("unchanged") where it opened.
Mapped to fill and colour by default.
changeThe close minus the open, i.e. direction as a
signed magnitude rather than a three-level factor. Useful for a
continuous colour or fill scale, e.g.
aes(fill = after_stat(change)), in place of the default discrete
direction mapping.
nThe number of observations summarised.
widthThe width of the candlestick's body, in data units.
geom_candlestick() understands the following aesthetics. Required aesthetics are displayed in bold and defaults are displayed for optional aesthetics:
| • | x or y | |
| • | lower or xlower | |
| • | upper or xupper | |
| • | ymin or xmin | |
| • | ymax or xmax | |
| • | alpha | → NA |
| • | colour | → via theme() |
| • | fill | → via theme() |
| • | group | → inferred |
| • | linetype | → via theme() |
| • | linewidth | → via theme() |
Learn more about setting these aesthetics in vignette("ggplot2-specs").
library(ggplot2)
prices <- data.frame(
time = mixtime::datetime(
as.POSIXct("2024-01-01", tz = "UTC") + (0:719) * 3600
),
price = 100 + cumsum(rnorm(720, 0, 0.5))
)
# Summarise hourly prices into daily candlesticks, coloured red/green by
# `direction` by default
ggplot(prices, aes(time, price)) +
geom_candlestick(granule = mixtime::days(1L))
# `granule` accepts a bare granule of the axis's own calendar
ggplot(prices, aes(time, price)) +
geom_candlestick(granule = hour(6L))
# Any other discrete diverging scale overrides the red/green default;
# `colour` needs its own scale too, or it stays red/green
ggplot(prices, aes(time, price)) +
geom_candlestick(granule = mixtime::days(1L)) +
scale_fill_brewer(type = "div", palette = "RdBu", drop = FALSE) +
scale_colour_brewer(type = "div", palette = "RdBu", drop = FALSE)
# Use after_stat(change) with a diverging colour scale for extent of change
ggplot(prices, aes(time, price)) +
geom_candlestick(
aes(fill = after_stat(change), colour = after_stat(change)),
granule = mixtime::days(1L)
) +
scale_fill_gradient2(low = "red", mid = "grey90", high = "green") +
scale_colour_gradient2(low = "red", mid = "grey90", high = "green")
# Already summarised prices can be plotted with stat = "identity"
set.seed(0)
close <- 100 + cumsum(rnorm(90))
ohlc <- data.frame(
time = mixtime::date(as.Date("2024-01-01") + 0:89),
open = c(100, close[-length(close)]),
close = close
)
ohlc$high <- pmax(ohlc$open, ohlc$close) + runif(90, 0, 2)
ohlc$low <- pmin(ohlc$open, ohlc$close) - runif(90, 0, 2)
ohlc$direction <- ifelse(sign(ohlc$close - ohlc$open) > 0, "rising", "falling")
ggplot(
ohlc,
aes(
x = time, fill = direction, colour = direction,
lower = open, upper = close,
ymin = low, ymax = high
)
) +
geom_candlestick(stat = "identity")
# Using stat = "ohlc" (the default) with complete OHLC data will
# compute the OHLC prices at coarser granules
ggplot(
ohlc,
aes(
x = time, lower = open, upper = close,
ymin = low, ymax = high
)
) +
geom_candlestick(granule = mixtime::cal_isoweek$week(1L))