0

Here is the code I have:

library("ggplot2") # Loading the req1uired packages
library("ggpubr")
rm(list=ls())
TeamsHalf <- read.table(file= "../data/TeamsHalf.txt", sep = ";", header = T) # Loading the data table

index = TeamsHalf$Half == 2   #Making a column with each teams' rank at the end of the season
TeamsHalf$FinalRank[index] <- TeamsHalf$Rank[index]     

TeamsHalf$divID <- as.factor(TeamsHalf$divID) # changing the order that facet_wrap orders the divisions, so that "East" is on the right-hand side of the plot
TeamsHalf$divID = names(TeamsHalf$divID) = c("Western ", "Eastern")
levels(TeamsHalf$divID) <- c("Eastern ","Western")

TeamsHalf$Half <- as.factor(TeamsHalf$Half) # Changing the order of the stacked bars so that the 1st half of the season is below 2nd half.
levels(TeamsHalf$Half) <- c("2","1")

g.TeamsHalfNL <- ggplot(data = TeamsHalf[TeamsHalf$lgID == "NL",], # Extracting data for the Eastern division
                       aes (y = W, x = reorder(teamID, -FinalRank, na.rm = T), fill = factor(Half)))+ # setting the name of the variables, reordering x in order of rank at the end of the season, and setting the colorss for the different halfs.
  geom_col(width = 0.8, position = "stack")+     # Setting the width of cols, and stacking them on top of each other.
  scale_colour_manual(values = c( "#002a5b", "#ffc78a"), aesthetics = c("color", "fill"))+ # changing the colors of the columns. 
  labs(x = "National League", y = "Wins", fill = "Season Half")+  # changing x and y labels, and the legend title.
  theme(
    panel.background = element_rect(fill = NA), # setting a white background
    panel.grid.major.y = element_line(colour = "grey50", size = 1/4), # Changing the size and color of the horizontal grid lines
    panel.grid.major.x = element_blank())+ # removing the vertical gridlines
  facet_wrap(.~divID, scales = "free") # splitting the plot into two graphs, one for each league

g.TeamsHalfAL <- ggplot(data = TeamsHalf[TeamsHalf$lgID == "AL",], # Extracting data for the Western division
                       aes (y = W , x = reorder(teamID, -FinalRank, na.rm = T), fill = factor(Half)))+ # setting the name of the variables, reordering x in order of rank at the end of the season, and setting the colorss for the different halfs.
  geom_col(width = 0.8, position = "stack")+    # Setting the width of cols, and stacking them on top of each other.
  scale_colour_manual(values = c( "#002a5b", "#ffc78a"), aesthetics = c("color", "fill"))+ # changing the colors of the columns.
  labs(x = "American League", y="Wins")+ # changing x and y labels, and the legend title.
  theme(
    
    panel.background = element_rect(fill = NA), # setting a white background
    panel.grid.major.y = element_line(colour = "grey50", size = 1/4), # # Changing the size and color of the horizontal grid lines
    panel.grid.major.x = element_blank())+ # removing the vertical gridlines
  facet_wrap(.~divID, scales = "free") # splitting the plot into two graphs, one for each league


FinalGraph <-  ggarrange(g.TeamsHalfAL, g.TeamsHalfNL, ncol = 1, nrow = 2, # combinging the two graphs, stacking them vertically
                         common.legend = T, legend = "bottom", align = "hv") # creating a shared legend, moving the legend, and aligning the graphs.


annotate_figure(FinalGraph, top = text_grob("\nOverview of the 1981 baseball season for AL and NL", face = "italic"), # Here, I set the text for title, note, and figure nr. the Title is indented with a "\n" to adhere to the APA style.
                bottom = text_grob("Note. The figure shows the number of wins for each team in the Western\n and Eastern division of the AL and NL. The teams are sorted by their final rank\n at the end of the season.", size = 8),
                fig.lab = "Figure 1")

I want the labels of the facet_wrap to say "Eastern" and "Western" instead of E and W, so I use the names() function to change them in line 10. However, when I do this, the facet_wrap makes two plots, but with all the same teams, instead of splitting them into western and Eastern. When I don't change the name of the variables, and they remain named "E" and "W", it works perfectly fine. Does anyone know what the issue is here?

Sverdo
  • 15
  • 4
  • 2
    You could improve your chances of finding help here by adding a [minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610). Adding a MRE and an example of the desired output (in code form, not tables and pictures) makes it much easier for others to find and test an answer to your question. That way you can help others to help you! P.S. Here is [a good overview on how to ask a good question](https://stackoverflow.com/help/how-to-ask) – dario Oct 14 '21 at 10:09
  • 1
    Also: I doubt that the `names` function does what you want it to do... I'd suggest looking into `ifelse`, `case` or `dplyr::recode` – dario Oct 14 '21 at 10:12
  • 1
    In addition to dario's comment; it is also good to leave out any code that is not necessary to reproduce the problem. In this case, we probably wouldn't need custom theme settings, non-default colour scales, legible titles or plot arrangements to encounter the problem. – teunbrand Oct 14 '21 at 11:45

1 Answers1

0

TL;DR - don't use names() for changing the factor labels. Instead, change the names of the facets in your plot within the plot code, as in:

... facet_wrap(~divID, labeller=as_labeller(c("E" = "Eastern", "W" = "Western"))...)

The line in your code where you use names() is not going to work:

TeamsHalf$divID = names(TeamsHalf$divID) = c("Western ", "Eastern")

First of all, the syntax is not correct, and more importantly, the names() function is not used for factor levels or labels = it's used for changing names of the "internal parts" of data structures. For example, names() can be used to rename columns in a data frame or items in a list.

The crux of your question is related to how to change the labels of the facets when using facet_wrap() or facet_grid(). Your example is not reproducible, so I'll use the built-in iris dataset to show you two fundamental approaches to do this.

The plot:

library(ggplot2)

p <- ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length)) + geom_point()
p + facet_wrap(~Species)

enter image description here

Use a Labeller Function

The most direct way to relabel facets is to use the labeller= argument of facet_wrap(...) or facet_grid(...). Here I use a named vector with the as_labeller() function to make sure the label names are applied correctly. Consequently, the order of the labels does not get controlled this way and the order of the facets is preserved.

p + facet_wrap(~Species,
      labeller = as_labeller(c(
         "setosa" = "First Facet",
         "virginica" = "Third Facet",
         "versicolor" = "Second Facet"
      )))

enter image description here

Change the names of the factor

The above method is more direct, but what you were attempting is similar to another approach that also should work. The caution here is that when using levels(...) you will need to make sure that the names you set for your facets are in the same order as they appear in the factor (df$Species). Consequently, this method is a bit more risky unless you're sure of the ordering of the levels of the particular factor:

df <- iris
df$Species <- factor(df$Species)

levels(df$Species) <- c("First", "Second", "Third")

ggplot(df, aes(x=Sepal.Width, y=Sepal.Length)) + geom_point() +
  facet_wrap(~Species)

enter image description here

In the end, remove your names() line in your code and I would recommend changing directly in the plot code. If your factor levels are called "E" and "W", then apply the labels you want with a named vector formatted with as_labeller() and applied via the labeller= argument inside facet_wrap(...).

chemdork123
  • 12,369
  • 2
  • 16
  • 32