ggplot2: Reversing the order of discrete categorie

2019-09-11 15:25发布

问题:

This question already has an answer here:

  • how to reverse order y-axis values in ggplot2 1 answer

I'm stuck trying to figure out how to revise this code so that in the scatterplot Architecture is on the top of the Y-axis and Visual Arts is on the bottom of the Y-axis.

UPDATE: With respect to the "duplicate" misclassification - My point was if there was an elegant way to do this WITHIN ggplot2, not simply reordering the levels in the data frame.

ggplot() + geom_point(aes(x = Year, y = Subclass_Name, colour = Subclass_Name, size = Transactions), data = art_data, alpha = 0.7)

Note: there was a similar question answered for a line plot but I can't make it work for the scatterplot: r - reverse order of discrete y axis in ggplot2

回答1:

You can reverse the order of the levels of your Subclass_name variable.

## Some sample data
art_data <- data.frame(Subclass_Name=sample(c("Architecture", "Painting", "Visual Arts"), 100, rep=T),
                  Year=sample(1920:2015, 100, rep=T, prob=sort(rexp(96, 1/8))),
                  Transactions=sample(1:7, 100, rep=T))

## Initial levels
levels(art_data$Subclass_Name)
# [1] "Architecture" "Painting"     "Visual Arts" 

## Reverse the order of Subclass_Name levels
art_data$Subclass_Name <- factor(art_data$Subclass_Name,
                                 levels=rev(levels(art_data$Subclass_Name)))
levels(art_data$Subclass_Name)
# [1] "Visual Arts"  "Painting"     "Architecture"

## Then make the plot
ggplot(art_data, aes(Year, Subclass_Name, color=Subclass_Name, size=Transactions)) +
  geom_point(alpha=0.7) +
  scale_color_discrete(breaks=rev(levels(art_data$Subclass_Name)),
                       labels=rev(levels(art_data$Subclass_Name)))  # reverse labels in legend