2010-07-15 74 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