Reordering columns by y-value in R?

我是研究僧i 提交于 2019-12-13 06:50:25

问题


I have a dataframe structured like this:

> head(df)
    Zip Crimes Population    CPC
1 78701   2103       6841 0.3074
2 78719    186       1764 0.1054
3 78702   1668      21334 0.0782
4 78723   2124      28330 0.0750
5 78753   3472      49301 0.0704
6 78741   2973      44935 0.0662

And I'm plotting it using this function:

p = ggplot(df, aes(x=Zip, y=CPC)) + geom_col() + theme(axis.text.x = element_text(angle = 90))

And this is the graph I get:

How can I order the plot by CPC, where the highest Zip codes are on the left?


回答1:


Convert Zip to a factor ordered by negative CPC. E.g., try df$Zip <- reorder(df$Zip, -df$CPC) before plotting. Here's a small example:

d <- data.frame(
  x = c('a', 'b', 'c'),
  y = c(5, 15, 10)
)

library(ggplot2)

# Without reordering
ggplot(d, aes(x, y)) + geom_col()

# With reordering
d$x <- reorder(d$x, -d$y)
ggplot(d, aes(x, y)) + geom_col()




回答2:


Sort your data frame in descending order and then plot it:

library(dplyr)
df <- arrange(df,desc(CPC))
ggplot...


来源:https://stackoverflow.com/questions/42288761/reordering-columns-by-y-value-in-r

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