0

I have been using ggplot geom_boxplot and arranging the x axis according to a specific order with scale_x_discrete resulting in a perfect plot. Then I try to arrange 4 of these plots using ggarrange, but that overrides the order of the groups. How can I do both? thank you

H_p<-ggplot (DiversData, aes(x=site, y=H, color=site)) +
  geom_boxplot()
H_p + scale_x_discrete(limits=c("Achziv", "SdotYam", "Sharon", "Ashdod", "Ashkelon")) +labs(title="Shannon fish diversity", x = "", y = "H", color = "Site") + theme_classic() + theme(legend.position="none")

One of the 4 original plots

Then when I tile them:

library(ggpubr)
require(grid)
ggarrange(p_vis2 + rremove("x.text")+ rremove("xlab"), H_p  + rremove("x.text")+ rremove("xlab"), S_p  + rremove("x.text")+ rremove("xlab"), J_p + rremove("x.text")+ rremove("xlab"),
                    labels = c("A", "B", "C", "D"),
                    ncol = 2, nrow = 2,common.legend = TRUE, legend = "bottom",
                    align = "hv", 
                    font.label = list(c("Achziv", "SdotYam", "Sharon", "Ashdod", "Ashkelon"),size = 10, color = "black", face = "bold", family = NULL, position = "top") )

The x axis goes back to ABC order

Thank you so much!

  • Welcome to SO, Anat! Unfortunately it's hard to figure out what's the issue as we don't have your data and a working example of your code. I already tried to create some fake example data but wasn't able to repdroduce your issue. Hence I would suggest to provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Dec 20 '22 at 07:58
  • Welcome to SO. As @stefan says, a reproducible example would be useful, but I anticipate that setting "site" to be a factor rather than character variable would allow you to set the order of the levels easily. – Paul Stafford Allen Dec 20 '22 at 08:01

1 Answers1

0

First, turn your 'site' column into a character vector (having not seen your existing dataset, I don't know if it's a character or factor, so this step may be redundant).

DiversData$site<- as.character(DiversData$site)

Secondly, turn it back to a factor with the levels in the desired order

DiversData$site<- factor(DiversData$site, levels=c("Achziv", "SdotYam", "Sharon", "Ashdod", "Ashkelon"))

then plot as before:

H_p<-ggplot (DiversData, aes(x=site, y=H, color=site)) +
  geom_boxplot()

etc

Paul Stafford Allen
  • 1,840
  • 1
  • 5
  • 16