datavoredan datavoredan - 16 days ago 5x
R Question

r ggplot - conditionally set aes element to NULL

I am building a wrapper function for ggplot to enable standard charts to be created with a single line of code.

One part of this is that in some cases the user will wish to set 'group' and 'color' aes elements, however in other cases they will not.

Is there a simple way of only having a 'group' or 'colour' aes element if the user passes one to the function, and to leave it blank otherwise?

I have tried simply setting these to to NULL, however this does not work, returning the following error.

Error: Aesthetics must be either length 1 or the same as the data (4): x, y, group, colour


Instead of NULL, try setting the aesthetic to 1.