trevorld / ggpattern

ggplot geoms with pattern fills
https://trevorldavis.com/R/ggpattern/dev/
Other
361 stars 18 forks source link

How to integrate patterns with stat_summary() ? #17

Closed barrel0luck closed 3 years ago

barrel0luck commented 4 years ago

I routinely use stat_summary in plotting as I like to plot both summarized data and all the data. For example I use stat_summary to make a bar plot and then geom_point/ geom_jitter to plot the points on the bars. (Box plots are not always a good alternative as they need larger data points and bars are nice as they're visually easy to compare, so I'm not looking for an alternative).

A typical plot of mine would look like this:

ggplot(dataset, aes(x = x_variable y = y_variable)) +
  facet_wrap(~some_grouping_variable) +
  stat_summary(fun = "mean", geom = "bar", aes(color = some_variable,     # Plots summarized (mean) barplot
                                               fill = some_variable,
                                               pattern = some_variable,
                                               pattern_color = some_variable)) +
  geom_point()                                                 # Plots all the data as points on the barplot

(Note pattern and pattern_color are not real options available and are just my dream options) So how do I add a pattern to the bars in stat_summary? This simple functionality that integrates well with existing plot objects is missing IMO in many of the patterning packages like ggpattern or ggtextures or I think there's a third one as well that I can't remember. Integrating with existing plot objects is essential so that patterning can be used with stat_summary.

coolbutuseless commented 3 years ago

patterns already work with stats. You need to ensure that you use a patterned geom as the 'geom' argument.

library(ggplot2)
library(ggpattern)
#> 
#> Attaching package: 'ggpattern'
#> The following objects are masked from 'package:ggplot2':
#> 
#>     flip_data, flipped_names, gg_dep, has_flipped_aes, remove_missing,
#>     should_stop, waiver

plot_df <- mtcars
plot_df$cyl <- as.factor(plot_df$cyl)

ggplot(plot_df, aes(x = am, y = wt)) +
  facet_wrap(~cyl) +
  stat_summary(fun = "mean", geom = "bar_pattern", aes(color = cyl, pattern = 'stripe', pattern_fill = cyl)) +
  geom_point() +
  theme(
    legend.position = 'none'
  )

Created on 2020-12-19 by the reprex package (v0.3.0)