Cauchy
Cauchy

Reputation: 1747

ggplot2: Change label for facet grouping variable in plot

This post shows how to make a facet with multiple scatter plots, but I am trying to change the name grp which is positioned on top of the group names and their corresponding colors, and I am trying to change it using a ggplot2 option without changing the names in the data frame. The reason I want to do this is that I want the new label shown to have a space in it. As an example I would want grp to be changed to The Groups.

Thanks for any help.

Upvotes: 1

Views: 3941

Answers (1)

Stibu
Stibu

Reputation: 15897

Since the question refers to this post, I will add the solution to the code given there:

  # get Petal.Length for each species separately    
  df1 <- subset(iris, Species == "virginica", select=c(Petal.Length, Species))
  df2 <- subset(iris, Species == "versicolor", select=c(Petal.Length, Species))
  df3 <- subset(iris, Species == "setosa", select=c(Petal.Length, Species))

  # construct species 1 vs 2, 2  vs 3 and 3 vs 1 data
  df <- data.frame(x=c(df1$Petal.Length, df2$Petal.Length, df3$Petal.Length), 
                   y = c(df2$Petal.Length, df3$Petal.Length, df1$Petal.Length), 
                   grp = rep(c("virginica.versicolor", "versicolor.setosa", "setosa.virginica"), each=50))
  df$grp <- factor(df$grp)

  # plot
  require(ggplot2)
  ggplot(data = df, aes(x = x, y = y)) + geom_point(aes(colour=grp)) + facet_wrap( ~ grp) +
     labs(colour="The Groups")

which leads to the following figure:

enter image description here

The part I added to set the legend title is +labs(colour="The Groups"). labs can be used to set titles to other aesthetics as well:

+ labs(x="x-axis title", y="y-axis title", fill="fill legend title", shape="shape legend title", colour="colour legend title")

and maybe others that I forgot.

One final remark: You asked to change the name of the "label for facet grouping variable". This is not actually what you wanted to do and what my solution does. It changes the label of the variable used for colouring (aes(colour=grp)). It so happens that this the same variable is also used for faceting (facet_wrap( ~ grp)).

Upvotes: 2

Related Questions