2017-03-05 104 views
0

我想通過x軸排序數據,這些數據是整數值(Crude.Rate =每種疾病的死亡數目),但是,美國的y軸正在按照字母順序保存數據。我試圖創建x軸數字數據的因子,但圖表保持按字母順序排列,x軸標籤只是左右移動以匹配y軸。在x軸上按數字數據排序ggplot條形圖,而不是在y軸上按字母順序排列

代碼:

stDis10 <- cdcData %>% 
    filter(Year == "2010", ICD.Chapter == "Heart Attack") %>% 
    arrange(desc(Crude.Rate)) %>% 
    select(State, ICD.Chapter, Crude.Rate) 

stDis10$Crude.Rate <- factor(stDis10$Crude.Rate, levels = stDis10$Crude.Rate) 

ggplot(stDis10, aes(y = Crude.Rate, x = State)) + geom_bar(stat='identity') + coord_flip() 

回答

0

你不需要Crude.Rate改變的一個因素。您可以通過Crude.Rate重新排序國家:

ggplot(stDis10, aes(y = Crude.Rate, x = reorder(State, Crude.Rate))) + geom_col() + coord_flip() 

(在GGPLOT2的最新版本,geom_col()可以用來代替geom_bar(stat = "identity")。)