Ryan
Ryan

Reputation: 33

Manually label axis in ggplot when using facet_wrap()

I am trying to manually label my x axis but when I facet my plots and free the scale of my x-axis, the labels become incorrect. I am wondering if there is anyway to prevent this without having to manually changing my the strings beforehand.

When I manually label the x-axis using scale_x_discrete() the labels are correct

library(tidyverse)

df <- data.frame(trial = rep(c("a", "b", "c"), each = 30),
                 values = rnorm(n = 90, mean = 0, sd = 1),
                 variable = c(rep("n", times = 60), rep("m", times = 30))
                 )

df %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  scale_x_discrete(labels = c("A", "B", "C")) +
  theme(legend.position = "none") 

Plot 1

However when I facet my plot the labels become incorrect.

df %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  scale_x_discrete(labels = c("A", "B", "C")) +
  facet_wrap(~ variable, scales = "free_x") +
  theme(legend.position = "none")

Plot 2

Upvotes: 3

Views: 1657

Answers (2)

akrun
akrun

Reputation: 887118

We can use fct_recode from forcats

library(forcats)
library(dplyr)
library(ggplot2)
df %>% 
   mutate(trial = fct_recode(trial, A= 'a', B = 'b', C = 'c'))  %>% 
  ggplot(aes(x = trial, y = values)) + 
       geom_violin(aes(fill = trial)) +
       facet_wrap(~ variable, scales = "free_x") + 
       theme(legend.position = "none")

-output

enter image description here

Upvotes: 0

Duck
Duck

Reputation: 39595

Try this:

library(ggplot2)
library(dplyr)
#Code
df %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  scale_x_discrete(breaks=c('a','b','c'),labels = c("A", "B", "C")) +
  facet_wrap(~ variable, scales = "free_x") +
  theme(legend.position = "none")

Output:

enter image description here

Or you can also try formating the variable with mutate():

#Code 2
df %>%
  mutate(trial=factor(trial,levels = unique(trial),labels = c("A", "B", "C"))) %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  facet_wrap(~ variable, scales = "free_x") +
  theme(legend.position = "none")

Same output. Or following the great advice from @cookesd (Many thanks and credit to him):

#Code 3
df %>%
  ggplot(aes(x = trial, y = values)) +
  geom_violin(aes(fill = trial)) +
  scale_x_discrete(labels = c('a' = 'A', 'b' = 'B', 'c' = 'C')) +
  facet_wrap(~ variable, scales = "free_x") +
  theme(legend.position = "none")

Same output.

Upvotes: 3

Related Questions