2010-07-15 70 views
84

我正在使用具有离散x比例的ggplot制作闪回条形图,x轴现在按字母顺序排列,但我需要重新排列它以便按照y轴(即最高的柱将位于左侧)。更改离散x比例的顺序

我尝试了命令或排序,但导致排序的x轴,但不是分别为酒吧。

我做错了什么?

回答

77

尝试手动设置x轴上的系数水平。例如:

library(ggplot2) 
# Automatic levels 
ggplot(mtcars, aes(factor(cyl))) + geom_bar()  

ggplot of the cars dataset with factor levels automatically determined

# Manual levels 
cyl_table <- table(mtcars$cyl) 
cyl_levels <- names(cyl_table)[order(cyl_table)] 
mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels) 
# Just to be clear, the above line is no different than: 
# mtcars$cyl2 <- factor(mtcars$cyl, levels = c("6","4","8")) 
# You can manually set the levels in whatever order you please. 
ggplot(mtcars, aes(cyl2)) + geom_bar() 

ggplot of the cars dataset with factor levels reordered manually

正如詹姆斯在他的回答中指出,reorder是重新排序因子水平的惯用方式。

mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x))) 
ggplot(mtcars, aes(cyl3)) + geom_bar() 

ggplot of the cars dataset with factor levels reordered using the reorder function

25

您可以使用reorder

qplot(reorder(factor(cyl),factor(cyl),length),data=mtcars,geom="bar") 

编辑:

要具有最高的酒吧在左边,你必须使用一个有点杂牌的:

qplot(reorder(factor(cyl),factor(cyl),function(x) length(x)*-1), 
    data=mtcars,geom="bar") 

我希望这也有负高度,但它不,所以它的工作原理!

+5

我震惊了这个答案没有更多upvotes,90%的时间,这是做的正确方法。 – Gregor 2015-11-03 02:00:10

+0

我认为这两个因素调用是多余的。有一个隐式调用来考虑第一个参数,第二个参数被假定为数字。 – 2017-09-16 16:38:32

134

对我来说,最好的方法是使用具有类别的向量,以便我需要limits参数到scale_x_discrete。我认为这是非常简单和直接的解决方案。

ggplot(mtcars, aes(factor(cyl))) + 
geom_bar() + 
scale_x_discrete(limits=c(8,4,6)) 

enter image description here

+1

这个“作品”....但传说仍然显示混乱的命令... – 2015-04-03 13:48:34

+0

@HendyIrawan没有传说,除非你有其他尺寸(颜色,填充)也映射到相同的变量。 – Gregor 2015-10-08 23:10:32

2

我意识到这是旧的,但也许这功能我创建是有用的人在那里:

order_axis<-function(data, axis, column) 
{ 
    # for interactivity with ggplot2 
    arguments <- as.list(match.call()) 
    col <- eval(arguments$column, data) 
    ax <- eval(arguments$axis, data) 

    # evaluated factors 
    a<-reorder(with(data, ax), 
      with(data, col)) 

    #new_data 
    df<-cbind.data.frame(data) 
    # define new var 
    within(df, 
     do.call("<-",list(paste0(as.character(arguments$axis),"_o"), a))) 
} 

现在,有了这个功能,您可以以交互方式GGPLOT2情节,像这样:

ggplot(order_axis(df, AXIS_X, COLUMN_Y), 
     aes(x = AXIS_X_o, y = COLUMN_Y)) + 
     geom_bar(stat = "identity") 

可以看出,order_axis函数创建了另一个数据框,并在最后列出了一个名为相同但具有_o的新列。这个新的列按升序排列,所以ggplot2自动按照这个顺序绘图。

这是有限的(只适用于字符或因子和数字组合的列和升序),但我仍然发现它非常有用的绘图在旅途中。

13

哈德利一直在开发名为forcats的软件包。这个软件包使得任务变得更加简单。如果要按x因子的频率更改x轴的顺序,则可以利用fct_infreq()。在本文中的mtcars示例中,您希望按每个级别的频率对cyl级别进行重新排序。出现频率最高的级别停留在左侧。所有你需要的是fct_infreq()

library(ggplot2) 
library(forcats) 

ggplot(mtcars, aes(fct_infreq(factor(cyl)))) + 
geom_bar() + 
labs(x = "cyl") 

如果你想绕走另一条路,你可以使用带有fct_infreq()一起fct_rev()

ggplot(mtcars, aes(fct_rev(fct_infreq(factor(cyl))))) + 
geom_bar() + 
labs(x = "cyl") 

enter image description here