2017-02-18 54 views
0

我的數據看起來像與項目在ggplot條形圖的傳說順序遇到問題

language tone  count tone_percent label_pos pos 
1 c   positive 3460 36.16977  18.08488 7 
2 c   neutral  2046 21.38825  46.86389 7 
3 c   negative 4060 42.44198  78.77901 7 
4 c#   positive 3732 41.26949  20.63475 3 
5 c#   neutral  1832 20.25876  51.39887 3 
6 c#   negative 3479 38.47175  80.76413 3 
7 c++   positive 3136 33.13960  16.56980 8 
8 c++   neutral  2008 21.21949  43.74934 8 
9 c++   negative 4319 45.64092  77.17954 8 

而且我一直在嘗試使用GGPLOT2條形圖想象他們:

p <-ggplot() + theme_bw() + geom_bar(aes(y=tone_percent, x=reorder(language, -pos), fill=tone), data=data, stat="identity") + 
    geom_text(data=data, aes(x = language, y = label_pos, ymax=label_pos, hjust = 0.5, label = paste0(round(tone_percent),"%")), size=4) + 
    labs(x="Language", y="Percentage of tone") + 
    scale_fill_manual(values=c('#F45E5A', '#5086FF', '#17B12B')) + 
    theme(legend.position="bottom", legend.direction="horizontal", legend.title = element_blank()) + coord_flip() 

它給出了幾乎優秀的結果: enter image description here

但是,圖例按字母順序顯示標籤,但我想以相同的順序顯示它們因爲條形圖在圖表中繪製:積極然後中性然後負數

有沒有什麼辦法可以實現這一點?

+0

這不是一個很好的欺騙;該方法也會改變條形的顏色順序,所以它們仍然不會與圖例對齊。 – alistaire

回答

2

可以傳遞的scale功能guide_legend(reverse = TRUE),這將扭轉傳奇順序沒有重新排序的酒吧guides參數。清理了一下:

ggplot(data, aes(x = reorder(language, -pos), y = tone_percent, fill = tone)) + 
    geom_col() + 
    geom_text(aes(y = label_pos, label = paste0(round(tone_percent),"%"))) + 
    coord_flip() + 
    labs(x = "Language", y = "Percentage of tone") + 
    scale_fill_manual(NULL, values=c('#F45E5A', '#5086FF', '#17B12B'), 
         guide = guide_legend(reverse = TRUE)) + 
    theme_bw() + 
    theme(legend.position = "bottom", 
      legend.direction = "horizontal") 

plot with correct legend

+0

這工作,謝謝一噸 – sovo2014

0

您需要格式化音調變量作爲一個因素。

data$tone <- factor(data$tone, levels=c("positive", "neutral", "negative"))

+0

謝謝,但「音」實際上是因素,我檢查了:> str(data) 'data.frame':\t 9 obs。 6個變量: $語言:因子w/8級別「c」,「c#」,「C++」,..:1 1 1 2 2 2 3 3 3 $ tone:因子w/3級別爲「negative」 「neutral」,..:3 2 1 3 2 1 3 2 1 $ count:int 3460 2046 4060 3732 1832 3479 3136 2008 4319 $ tone_percent:num 36.2 21.4 42.4 41.3 20.3 ... $ label_pos:num 18.1 46.9 78.8 20.6 51.4 ... $ pos:int 7 7 7 3 3 3 8 8 8 – sovo2014

+0

@ sovo2014您需要通過指定控制順序的級別來對其進行格式化。檢查'水平(數據$口氣)' –