1
votes

I'm trying to get a variable geom type using ggplot2 in a Shiny plot.

if (type == "column") {
    geom <- geom_col() 
} else {
    geom <- geom_line() + geom_point()
}

qplot(1:10, 1:10) + geom

This works if we remove the "geom_point" however combining them doesn't return the expression but is rather evaluated separately (which is impossible: cannot add ggproto objects together). Is there some sort of work around that doesn't require storing the plot and then adding the geom?

1
I can't reproduce it, but just a wild guess what happens if you wrap the else with a list as follows: geom <- list(geom_line() + geom_point())? - deepseefan
No good sorry: still tries to evaluate geom_col() + geom_point() inside the list function which is still impossible. - Daniel V

1 Answers

2
votes

It does work if you store the geoms in a list

my_geom <- function(type)
    if (type == "column") list(geom_col()) else list(geom_line(), geom_point())

qplot(1:10, 1:10) + my_geom("column")

enter image description here

qplot(1:10, 1:10) + my_geom("other")

enter image description here