简体   繁体   中英

Modify labels in facet_grid on existing ggplot2 object

Suppose we have the following dataset:

d = data.frame(
  y = rnorm(100),
  x = rnorm(100),
  f1 = sample(c("A", "B"), size=100, replace=T)
)

And I want to plot the data using facets:

require(ggplot2)
plot = ggplot(d, aes(x,y)) +
  facet_grid(~f1, labeller = labeller(.cols=label_both))

Now let's suppose I want to capitalize all columns. It's trivial to do so with the x/y variables:

plot + labs(x="X", y="Y")

But how do I go about capitalizing the facet labels?

The obvious solutions are:

  1. Just change the name of the variable (eg, d$F1 = d$f1 ) then rerun the code.
  2. Create a custom labeller that capitalizes the variable names

However, I cannot do either of these in my current application. I cannot change the original ggplot object; I can only layer (eg, as I do with the x/y axis labels) or I can modify the ggplot object directly.

So, is there a way to change the facet labels by either modifying the ggplot object directly or layering it?

Fortunately, I was able to solve my own problem by creating my MWE. And, rather than keep that knowledge to myself, I figured I'd share it with others (or future me if I forget how to do this).

ggplot objects can be easily dissected using str

In this case, the ggplot object ( plot ) can be dissected:

str(plot)

Which lists many objects, including one called facet , which can be further dissected:

str(plot$facet)

After some trial and error, I found an object called plot$facet$params$cols . Now, using the following code:

names(plot$facet$params$cols) = "F1"

I get the desired result.

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