2012-07-09 161 views
53

有沒有人知道我可以如何控制ggplot2中的圖例排序?控制ggplot2圖例顯示順序

從我所看到的順序看起來與實際比例標籤相關,而不是比例尺聲明順序。更改比例標題會改變順序。我用鑽石數據集做了一個小例子來強調這一點。我正在嘗試使用ggplot2進行一系列的繪圖,並且我想讓其中的一個變量出現在右側。目前,雖然這隻發生在其中的一些,並且我在如何執行我想要的訂購時仍然感到茫然,同時保留適當的比例標籤。

library(ggplot2) 
diamond.data <- diamonds[sample(nrow(diamonds), 1000), ] 
plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) + 
    geom_point() + opts(legend.position = "top", legend.box = "horizontal") 
plot # the legend will appear shape then colour 
plot + labs(colour = "A", shape = "B") # legend will be colour then shape 
plot + labs(colour = "Clarity", shape = "Cut") # legend will be shape then colour 
+2

相關(儘管這個問題有一個更好的解決方案):http://stackoverflow.com/questions/10035551 /多重傳奇 - 指南 - 什麼是自動邏輯 - 如何改變 – 2012-07-09 16:12:53

回答

87

在0.9.1中,確定圖例順序的規則是祕密不可預知。 現在,在github的0.9.2版本中,您可以使用參數來設置圖例的順序。

這裏是例如:

plot <- ggplot(diamond.data, aes(carat, price, colour = clarity, shape = cut)) + 
    geom_point() + opts(legend.position = "top") 

plot + guides(colour = guide_legend(order = 1), 
       shape = guide_legend(order = 2)) 

enter image description here

plot + guides(colour = guide_legend(order = 2), 
       shape = guide_legend(order = 1)) 

enter image description here

12

在我看來,圖例的順序是由刻度名稱中的字符數決定的。 (是的,我同意,這似乎離奇。)

所以,一個解決辦法是墊您的標籤用空格:

plot + labs(colour = "Clarity", shape = "  Cut") 

enter image description here


我真誠地希望有人張貼一個妥善的解決辦法不久!

+0

我得到清晰,然後在我的傳說中剪切(用空格填充),如果我做wha你做到了。 packageDescription(「ggplot2」)$ Version = 0.9.1 – Spacedman 2012-07-09 12:45:04

+0

我應該清楚說明我實際上需要顏色然後是形狀(即清晰度然後切割),而不是切割然後是清晰度類似於您的示例。但是,我希望能夠對任何尺寸進行命名並仍然具有該順序。 – Alastair 2012-07-09 13:31:49

+4

@Alastair現在很清楚,我的解決方法只能在'ggplot2'版本0.9.0中使用 - 此解決方法不再適用於0.9.1版本。因此,如果您仍然使用0.9.0,則可以用空格填充字符串以獲得所需的順序。正如我所說,這只是一種解決方法(並且保質期有限)。 – Andrie 2012-07-09 13:37:31