2017-02-17 40 views
0

我有一个数据帧结构是这样的:用R中的y值重新排列列?

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

这是图我得到:

p

如何按CPC订购图表,最高的邮政编码位于左侧?

+0

@SimonJackson工作就像一个魅力!如果您将该评论发布为答案,我会对其进行检查:) –

+1

Simon的答案是,按照CPC对数据框进行排序,然后使用Hadley的forcats软件包中的fct_inorder函数。 – thc

+0

完成后,我发布了使用'reorder()'作为答案,并删除了我的评论,以免双倍下沉! @thc的建议也很好。 –

回答

2

将Zip转换为按负排序CPC排序的因子。例如,在绘图之前尝试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() 

enter image description here

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

enter image description here

0

按降序排列您的数据帧,然后绘制它:

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