Serenthia Serenthia - 22 days ago 6
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

geom_text
sets. I had naively thought that because the
+
operator is overloaded by ggplot, I may be able to call
sum()
on a list of
geom_text
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
geom_bar
as well if required...

Answer

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

baseplot + geomBar + geomtextList + …