0

I want to create a plot where the two facets have (i) different x-axes and (ii) the order or the x-axis is maintained from the order of occurrence in the dataframe.

Sample code:

part <- as.factor(c("A","A","A","B","B","B"))
word <- c("dog", "cat", "fish", "hamster", "dog", "eagle")
order <- c(1,2,3,4,5,6)
val <- c(1,2,3,3,2,1)
df <- as.data.frame(cbind(part,order,word,val))
ggplot(df, aes(x=word, y=val))+
facet_wrap(part, scales = "free_x")+ 
geom_point()

Which produces this plot.

But, the order isn't the same as what's specified in the word variable. The order of words should be "dog", "cat", "fish" for Part A and "hamster", "dog", "eagle" for Part B.

I can get the correct order when I

plot order on the x-axis instead.

But I want the corresponding words to be on the x-axis... What am I doing wrong?

I have checked out other related solutions like this one, but 'scales = "free_x"' doesn't do the trick by itself. Also, if I change "word" into an ordered factor, it runs into issues too, since "dog" is the first word in Part A but the second word in Part B.

akrun
  • 874,273
  • 37
  • 540
  • 662
  • Possible duplicate of https://stackoverflow.com/questions/14262497/fixing-the-order-of-facets-in-ggplot – akrun Feb 16 '23 at 21:14

1 Answers1

1

With this particular data set you could just do:

df %>%
  ggplot(aes(factor(word, c("hamster", "dog", "cat", "fish", "eagle")), val)) +
  facet_wrap(part, scales = "free_x") + 
  labs(x = "word") +
  geom_point()

enter image description here

Though a more general solution for this setup would be to make the x axis numeric and apply all the values of "word" as labels to the axis:

ggplot(df, aes(seq_along(word), val)) +
  facet_wrap(part, scales = "free_x") + 
  scale_x_continuous("word", breaks = seq(nrow(df)), labels = df$word,
                     expand = c(0.3, 0)) +
  geom_point()

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87