hadley / ggplot2-book

ggplot2: elegant graphics for data analysis
https://ggplot2-book.org/
1.57k stars 684 forks source link

Add instructions for creating a ggplot function that can be chained #375

Closed warnes closed 1 year ago

warnes commented 1 year ago

Please add a sub-section showing the proper way to create a function that can be chained with ggplot.

For instance, I have an annotation I want to add to several plots that consists of a line segment lying on the x axis, with a label above it representing events that occur along the time (x) axis.

In my original plot, this is accomplished by adding (with +) calls to geom_segment and annotate.

How can these two steps be properly encapsulated into a function (say, add_event) that can be chained like so:

ggplot(data_combined, aes(x=`Month`, y=`New Members`)) +
  geom_point(color=2, shape=15) +
  geom_line(color= 2) + 
  scale_y_continuous(limits=c(0,max(cfcu_business$`New Members`))) +
  add_event('Impact of Covid', xstart = startDate, xend = endDate)  +
  theme(plot.title = element_text(hjust = 0.5))
hadley commented 1 year ago

Like https://ggplot2-book.org/programming#multiple-components ?

warnes commented 1 year ago

Thanks, it looks like I must have been looking at an out-of-date version.