Reputation: 1015
I want to make a plot with faceting. The data is very straight-forward for this minimally reproducible example(and just as much in the original):
structure(list(Phenotype = c("Dichaete", "Dichaete", "Wild",
"Wild"), Status = c("Observed", "Expected", "Observed", "Expected"
), Results = c(773, 885.75, 408, 295.25)), row.names = c(NA,
-4L), class = c("tbl_df", "tbl", "data.frame"))
Now, there are two parts on this code: one is what I did to simulate other variables I have. Those won't change. The other part is entirely flexible.
# Unchangeable Part ############################
fly <- tibble(Phenotype = c("Dichaete", "Wild"),
Observed = c(773, 408),
Expected = c(885.75, 295.25))
data <- pivot_longer(fly, cols = c(Observed, Expected), names_to = "Status", values_to = "Results")
gfIdentifier <- "Phenotype"
# Changeable Part ##############################
ggplot(data, aes(x = Status, y = Results, fill = Status))+
geom_col(colour = "black")+
facet_wrap(facets = .data[[gfIdentifier]], ncol = 2)+
theme_classic()
That code produces this plot (I added the colour = "black"
argument to illustrate my point):
It doesn't do the faceting. What I wanted was this:
(I already took out the black border)
Note that all the variables I described in the beginning can and will change, so explicitly mentioning them (as I did to create the goal) isn't an option.
Upvotes: 1
Views: 313
Reputation: 1052
I love this question because it was a horrible pain for me to figure out when I was dealing with a similar situation, but its such a nice solution that actually ends up being applicable to tons of cool stuff. All you have to do is make R treat your text string as a variable. This can be done using eval and parse.
ggplot(data, aes(x = Status, y = Results, fill = Status))+
geom_col(colour = "black")+
facet_wrap(.~eval(parse(text = gfIdentifier)), ncol = 2)+
theme_classic()
Upvotes: 2