Serenthia Serenthia - 3 months ago 22
R Question

Passing in an unknown number of "geom_text"s to ggplot as function parameters

I'd like to wrap chart creation in my own function that ultimately creates a ggplot object. This is to reduce code repetition. Because various charts may have different requirements, there are a few parameters.

One variation between different charts may be displaying one or more

sets. I had naively thought that because the
operator is overloaded by ggplot, I may be able to call
on a list of
objects as follows:

outputPlot <- basePlot +
geomBar +
sum(geomTextList) +
titles +
theme +
yScale +
plotFill +
if (coordFlip) { coord_flip() } else { NULL }

However, this returns
Error in sum(geomTextList) : invalid 'type' (list) of argument

Does anyone have any ideas for how I might be able to achieve this, or am I just shooting for the moon? It also ultimately extends to having a list of
as well if required...


No need for sum: ggplot2 can deal with lists of layers so the following should work:

baseplot + geomBar + geomtextList + …