在 R 中按 y 值重新排序列?

Reordering columns by y-value in R?

我有一个结构如下的数据框:

> 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

我正在使用这个函数绘制它:

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

这是我得到的图表:

如何按 CPC 排序地块,最高的邮政编码在左边?

将 Zip 转换为按负每次点击费用排序的因素。例如,在绘图之前尝试 df$Zip <- reorder(df$Zip, -df$CPC)。这是一个小例子:

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()

按降序对数据框进行排序,然后绘制它:

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