This statistic is intended to be used with two discrete variables
mapped to x and y aesthetics. It will
compute several statistics of a cross-tabulated table using
More precisely, the computed variables are:
stat_cross() is using
ggplot2::geom_points(). If you want to plot the number of
observations, you need to map
after_stat(observed) to an
aesthetic (here size):
Note that the weight aesthetic is taken into account
We can go further using a custom shape and filling points with standardized residual to identify visually cells who are over- or underrepresented.
We can easily recreate a cross-tabulated table.
Even more complicated, we want to produce a table showing column
proportions and where cells are filled with standardized residuals. Note
stat_cross() could be used with facets. In that case,
computation is done separately in each facet.
ggplot(d) + aes( x = Class, y = Survived, weight = Freq, label = scales::percent(after_stat(col.prop), accuracy = .1), fill = after_stat(std.resid) ) + stat_cross(shape = 22, size = 30) + geom_text(stat = "cross") + scale_fill_steps2(breaks = c(-3, -2, 2, 3), show.limits = TRUE) + facet_grid(rows = vars(Sex)) + labs(fill = "Standardized residuals") + theme_minimal()