2017-09-07 36 views
1

這裏是集: https://www.dropbox.com/s/mrlfnh6e2ww1xwd/home.csv?dl=0BARCHART重新安排使用ggplot不能正常工作

這裏是我的代碼:

hom <- read.csv(file.choose(),header=TRUE) 
home.melt <- melt(hom, id.vars='home') 

ggplot(home.melt, 
aes(x = reorder(home, value), y = value, 
fill=forcats::fct_rev(variable))) + 
geom_bar(stat = "identity",width = 0.8) + coord_flip() + 
theme_minimal(base_size=10) + 
labs(title="Home time", 
    subtitle="By matches", 
    x="Home", 
    y="time (minutes)", 
    fill=" ") 

這裏是輸出:

enter image description here

,你可以看到它沒有下降的順序。

+1

重新排序軸或填充? – PoGibas

+0

雲存儲鏈接不鼓勵,因爲它們會隨着時間的推移而崩潰。 –

+0

根據總時間對條進行重新排序。 'St'應該在頂部,然後'Ln'等。 – user709413

回答

2

的關鍵是指定函數調用進行重新排序:

reorder(home, value, FUN = sum) 

默認是 「的意思是」

ggplot(home.melt, 
       aes(x = reorder(home, value, FUN = sum), y = value, 
        fill=forcats::fct_rev(variable))) + 
      geom_bar(stat = "identity",width = 0.8) + coord_flip() + 
      theme_minimal(base_size=10) + 
      labs(title="Home time", 
       subtitle="By matches", 
       x="Home", 
       y="time (minutes)", 
       fill=" ") 
+0

完成先生!工作正常。 – user709413

1
library(data.table) 
library(ggplot2) 

hom <- fread("home.csv") 
home.melt <- melt(hom, "home") 
home.melt[, variable := factor(variable, levels = sort(unique(variable), decreasing = TRUE))] 

ggplot(home.melt, aes(home, value, fill = variable)) + 
    geom_bar(stat = "identity",width = 0.8) + 
    coord_flip() + 
    theme_minimal(base_size = 10) + 
    scale_x_discrete(limits = home.melt[, sum(value), home][order(V1), home]) + 
    scale_fill_brewer(palette = "Dark2") + 
    labs(title = "Home time", 
     subtitle = "By matches", 
     x = "Home", 
     y = "Time (minutes)", 
     fill = NULL) 

enter image description here

+0

感謝您的幫助,但這不是降序。 'St'應該在頂部,然後'Ln'等。 – user709413

+0

@ user709413,編輯,這是你想要的嗎? – PoGibas

+0

差不多!唯一的問題是,如果你看到我的原始圖表,你會注意到a1,a2,a3,... b7以某種順序堆疊,例如,a1離y軸最近,而b7離y最遠-軸。除了你的代碼之外,我還想保留這些內容。 – user709413