ggplot2: Reversing the order of discrete categories on y-axis in scatterplot [duplicate]

元气小坏坏 提交于 2019-12-13 22:03:51

问题


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



来源:https://stackoverflow.com/questions/31955772/ggplot2-reversing-the-order-of-discrete-categories-on-y-axis-in-scatterplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!