Ggplot2: Reversing the order of a discrete symbol variable for each face in a free scale?

I would like to build a faceted graph ggplot2. the x axis is continuous, the y axis is a list of animals. Two variables are constructed and faceted according to the behavior of the food.

The y-axis is on a free scale because each animal appears in only one category of behavior in food.

library(ggplot2)

# First clean up the data set:
msleep.noNA <- msleep[!is.na(msleep$vore),]
msleep.noNA.red <-  msleep.noNA[c(1,3,6,7)]
msleep.noNA.red <- msleep.noNA.red[!is.na(msleep.noNA.red[4]),]
msleep.noNA.red <- melt(msleep.noNA.red)

pg <- ggplot(msleep.noNA.red, aes(value, name, colour = variable)) +
      geom_point() +
      facet_grid(vore ~ ., scale="free_y", space = "free_y")
pg

# Try to reverse order of the y axis:
pg + scale_y_reverse()

# Not possible because its a factor, but it not classified as such:
class(msleep.noNA.red$name)

Does anyone have any clues as to how I can make a list of animal names in alphabetical order on each subplot?

+5
source share
1 answer

You can convert the row vector to a coefficient and specify the order of the levels:

The following command will create the factor. Levels are reduced in alphabetical order:

msleep.noNA.red <- within(msleep.noNA.red,
                         name <- ordered(name, levels = rev(sort(unique(name)))))

Now you can build the data:

pg <- ggplot(msleep.noNA.red, aes(value, name, colour = variable)) +
  geom_point() +
  facet_grid(vore ~ ., scale="free_y", space = "free_y")

enter image description here

+8

All Articles