stat_weighted_mean {ggstats} | R Documentation |
Compute weighted y mean
Description
This statistic will compute the mean of y aesthetic for each unique value of x, taking into account weight aesthetic if provided.
Usage
stat_weighted_mean(
mapping = NULL,
data = NULL,
geom = "point",
position = "identity",
...,
na.rm = FALSE,
orientation = NA,
show.legend = NA,
inherit.aes = TRUE
)
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 |
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 |
Value
A ggplot2
plot with the added statistic.
Computed variables
- y
weighted y (numerator / denominator)
- numerator
numerator
- denominator
denominator
See Also
vignette("stat_weighted_mean")
Examples
library(ggplot2)
data(tips, package = "reshape")
ggplot(tips) +
aes(x = day, y = total_bill) +
geom_point()
ggplot(tips) +
aes(x = day, y = total_bill) +
stat_weighted_mean()
ggplot(tips) +
aes(x = day, y = total_bill, group = 1) +
stat_weighted_mean(geom = "line")
ggplot(tips) +
aes(x = day, y = total_bill, colour = sex, group = sex) +
stat_weighted_mean(geom = "line")
ggplot(tips) +
aes(x = day, y = total_bill, fill = sex) +
stat_weighted_mean(geom = "bar", position = "dodge")
# computing a proportion on the fly
if (requireNamespace("scales")) {
ggplot(tips) +
aes(x = day, y = as.integer(smoker == "Yes"), fill = sex) +
stat_weighted_mean(geom = "bar", position = "dodge") +
scale_y_continuous(labels = scales::percent)
}
library(ggplot2)
# taking into account some weights
if (requireNamespace("scales")) {
d <- as.data.frame(Titanic)
ggplot(d) +
aes(
x = Class, y = as.integer(Survived == "Yes"),
weight = Freq, fill = Sex
) +
geom_bar(stat = "weighted_mean", position = "dodge") +
scale_y_continuous(labels = scales::percent) +
labs(y = "Survived")
}