Compute weighted y mean
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 |
Use to override the default connection between
|
position |
Position adjustment, either as a string, or the result of a call to a position adjustment function. |
... |
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 |
weighted y (numerator / denominator)
numerator
denominator
# Small function to display plots only if it's interactive
p_ <- GGally::print_if_interactive
data(tips, package = "reshape")
p_(ggplot(tips) +
aes(x = day, y = total_bill) +
geom_point())
p_(ggplot(tips) +
aes(x = day, y = total_bill) +
stat_weighted_mean())
p_(ggplot(tips) +
aes(x = day, y = total_bill, group = 1) +
stat_weighted_mean(geom = "line"))
p_(ggplot(tips) +
aes(x = day, y = total_bill, colour = sex, group = sex) +
stat_weighted_mean(geom = "line"))
p_(ggplot(tips) +
aes(x = day, y = total_bill, fill = sex) +
stat_weighted_mean(geom = "bar", position = "dodge"))
# computing a proportion on the fly
p_(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))
# taking into account some weights
d <- as.data.frame(Titanic)
p_(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"))
## Not run:
cuse <- read.table("https://data.princeton.edu/wws509/datasets/cuse.dat", header = TRUE)
cuse$n <- cuse$notUsing + cuse$using
cuse$prop <- cuse$using / cuse$n
ggplot(cuse) +
aes(x = education, y = prop, weight = n) +
stat_weighted_mean()
ggplot(cuse) +
aes(x = age, y = prop, weight = n, color = education) +
stat_weighted_mean()
ggplot(cuse) +
aes(x = education, y = prop, weight = n) +
stat_weighted_mean(geom = "bar")
# add percentages above each bar
ggplot(cuse) +
aes(x = age, y = prop, weight = n, fill = education) +
stat_weighted_mean(geom = "bar") +
geom_text(aes(label = scales::percent(after_stat(y))), stat = "weighted_mean", vjust = 0) +
facet_grid(~ education)
## End(Not run)Please choose more modern alternatives, such as Google Chrome or Mozilla Firefox.