简体   繁体   中英

How to make facet_wrap() for a column with its name stored in a variable

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM