用R中的y值重新排列列? [英] Reordering columns by y-value in R?

查看:227
本文介绍了用R中的y值重新排列列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的数据框:

 > (df)
邮编犯罪人口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

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

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

这是图我得到:





我如何按每次点击费用排序,最高的邮政编码在左边?

解决方案

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

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


library(ggplot2)

#不需要重新排序
ggplot(d,aes(x,y))+ geom_col()

 #重新排序
d $ x < - reorder(d $ x, -d $ y)
ggplot(d,aes(x,y))+ geom_col()


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?

解决方案

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

这篇关于用R中的y值重新排列列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆