How can I change the column name passed to "fill" programmatically?

271 views Asked by At

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

2

There are 2 answers

0
Artem Sokolov On

rlang::sym takes a string and converts it to a symbol. You just need to unquote it using !!, because aes expects unevaluated expressions:

library(rlang)

gg <- ggplot( df_plot, aes(x=year, y=`Pctge CC`, fill = !!sym(this_group_label)) )
gg <- gg + geom_area(position = "stack")
gg
3
ben On

This works:

this_group_label <- "Roots & Tubers"
#[...lots of code in which a data frame df_plot is created with a column named "Roots & Tubers...]"
fill_label <- paste0("`", this_group_label, "`")
gg <- ggplot(df_plot, aes_string("year", "`Pctge CC`", fill = fill_label))
gg <- gg + geom_area(position = "stack")
gg

Note the backticks around Pctge CC are also necessary for this to work.