I need to plot an area stack chart where the fill can be changed programmatically by changing a "string holder" variable. Here is an example of what I'd like to do.
this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes(x = year, y = `Pctge CC`, fill = this_group_label))
gg <- gg + geom_area(position = "stack")
gg
So that I could then change the string stored in this_group_label
when dealing with a new data frame with a different column name.
I have tried aes_string()
this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes_string("year", "`Pctge CC`", fill = this_group_label))
gg <- gg + geom_area(position = "stack")
gg
and get()
this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
gg <- ggplot(df_plot, aes(x = year, y = `Pctge CC`, fill = get(this_group_label)))
gg <- gg + geom_area(position = "stack")
gg
to no avail. When I try these last two I am getting the error Error in FUN(X[[i]], ...) : object 'Roots' not found
rlang::sym
takes a string and converts it to a symbol. You just need to unquote it using!!
, becauseaes
expects unevaluated expressions: