stat_prop {ggstats} | R Documentation |
Compute proportions according to custom denominator
Description
stat_prop()
is a variation of ggplot2::stat_count()
allowing to
compute custom proportions according to the by aesthetic defining
the denominator (i.e. all proportions for a same value of by will
sum to 1). The by aesthetic should be a factor. If by is not
specified, proportions of the total will be computed.
Usage
stat_prop(
mapping = NULL,
data = NULL,
geom = "bar",
position = "fill",
...,
width = NULL,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE,
complete = NULL
)
Arguments
mapping |
Set of aesthetic mappings created by |
data |
The data to be displayed in this layer. There are three options: If A A |
geom |
Override the default connection with |
position |
Position adjustment, either as a string naming the adjustment
(e.g. |
... |
Other arguments passed on to |
width |
Bar width. By default, set to 90% of the |
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 |
complete |
Name (character) of an aesthetic for those statistics should be completed for unobserved values (see example) |
Value
A ggplot2
plot with the added statistic.
Aesthetics
stat_prop()
understands the following aesthetics
(required aesthetics are in bold):
-
x or y
by (this aesthetic should be a factor)
group
weight
Computed variables
- count
number of points in bin
- prop
computed proportion
See Also
vignette("stat_prop")
, ggplot2::stat_count()
. For an alternative
approach, see
https://github.com/tidyverse/ggplot2/issues/5505#issuecomment-1791324008.
Examples
library(ggplot2)
d <- as.data.frame(Titanic)
p <- ggplot(d) +
aes(x = Class, fill = Survived, weight = Freq, by = Class) +
geom_bar(position = "fill") +
geom_text(stat = "prop", position = position_fill(.5))
p
p + facet_grid(~Sex)
ggplot(d) +
aes(x = Class, fill = Survived, weight = Freq) +
geom_bar(position = "dodge") +
geom_text(
aes(by = Survived),
stat = "prop",
position = position_dodge(0.9), vjust = "bottom"
)
if (requireNamespace("scales")) {
ggplot(d) +
aes(x = Class, fill = Survived, weight = Freq, by = 1) +
geom_bar() +
geom_text(
aes(label = scales::percent(after_stat(prop), accuracy = 1)),
stat = "prop",
position = position_stack(.5)
)
}
# displaying unobserved levels with complete
d <- diamonds %>%
dplyr::filter(!(cut == "Ideal" & clarity == "I1")) %>%
dplyr::filter(!(cut == "Very Good" & clarity == "VS2")) %>%
dplyr::filter(!(cut == "Premium" & clarity == "IF"))
p <- ggplot(d) +
aes(x = clarity, fill = cut, by = clarity) +
geom_bar(position = "fill")
p + geom_text(stat = "prop", position = position_fill(.5))
p + geom_text(stat = "prop", position = position_fill(.5), complete = "fill")