1

I am trying to order the bars as "0", "5", "10", "20". The basic ggplot() keeps placing the bars out of order. Here is my code:

data <- data.frame(
  Treatment=c("0","5", "10","20") ,  
  Salinity=c(21.8,22.5, 22.5, 23.5))

ggplot(data, aes(Treatment, Salinity, fill = x)) +   
  geom_bar(stat = "identity") +
  ylim(0,25)+
  ggtitle("Salicornia pacifica" )

And output Places the bars as "0", "10", "20", "5"

How do I set the order I want the bars, or rearrange the bars? enter image description here

stefan
  • 90,330
  • 6
  • 25
  • 51
kyliec
  • 21
  • 1
  • 3

2 Answers2

1

You can order the data columns into an arbitrary order using factors like this:

data1 <- data                                                 # Replicate original data
data1$x <- factor(data1$x,                                    # Change ordering manually
                  levels = c("0", "5", "10", "20"))

ggplot(data1, aes(x, y)) +                                    # Manually ordered barchart
  geom_bar(stat = "identity")
ethanknights
  • 154
  • 5
1

The issue is that your Treatment column is a character. Hence, ggplot2 will by default order the categories in alphabetical order . And alphabetically any string starting with a "2", e.g. "20" comes before a string starting with a "5".

To prevent that you have to convert to a factor with the levels set in your desired order, which in your case could be achieved by first converting to a numeric and afterwards to a factor:

library(ggplot2)

ggplot(data, aes(factor(as.numeric(Treatment)), Salinity)) +
  geom_bar(stat = "identity") +
  ylim(0, 25) +
  ggtitle("Salicornia pacifica")

stefan
  • 90,330
  • 6
  • 25
  • 51