View source: R/stat_weighted_mean.R
stat_weighted_mean | R Documentation |
This statistic will compute the mean of y aesthetic for each unique value of x, taking into account weight aesthetic if provided.
stat_weighted_mean(
mapping = NULL,
data = NULL,
geom = "point",
position = "identity",
...,
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 |
Override the default connection with |
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 |
orientation |
The orientation of the layer. The default ( |
show.legend |
logical. Should this layer be included in the legends?
|
inherit.aes |
If |
A ggplot2
plot with the added statistic.
weighted y (numerator / denominator)
numerator
denominator
vignette("stat_weighted_mean")
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")
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.