2016-04-13 18 views
5

我想證明ggplot中的多個傳說,但沒有任何真正的成功。在繪圖區域外顯示圖例(灰色區域)時,對齊是正確的。但是,在繪圖區域內顯示圖例時,圖例居中(我想讓它們左對齊)。我試圖按照this thread,但它仍然無法正常工作。多個傳說辯解

我的例子:

library(ggplot2) 

ggplot(mtcars, aes(wt, mpg)) + 
    geom_point(aes(colour = factor(cyl), size = qsec)) + 
    geom_point(aes(colour = factor(cyl), size = qsec)) + 
    theme(legend.justification = c(1,0), 
     legend.position = c(1,0), 
     legend.margin = unit(0,"lines"), 
     legend.box = "vertical", 
     legend.key.size = unit(1,"lines"), 
     legend.text.align = 0, 
     legend.title.align = 0) 

回答

5

我們需要添加legend.box.just = "left"到現有theme()

ggplot(mtcars, aes(wt, mpg)) + 
    geom_point(aes(colour = factor(cyl), size = qsec)) + 
    geom_point(aes(colour = factor(cyl), size = qsec)) + 
    theme(legend.box.just = "left", 
     legend.justification = c(1,0), 
     legend.position = c(1,0), 
     legend.margin = unit(0,"lines"), 
     legend.box = "vertical", 
     legend.key.size = unit(1,"lines"), 
     legend.text.align = 0, 
     legend.title.align = 0) 

enter image description here

+0

感謝您的快速回復。這個完全解決了我的問題! – Adela

1

你可以試試這個:

library(ggplot2) 
data("mtcars") 
g <- ggplot(mtcars, aes(wt, mpg)) 
g <- g + geom_point(aes(colour = factor(cyl), size = qsec)) 
g <- g + geom_point(aes(colour = factor(cyl), size = qsec)) 
g <- g + theme(legend.justification=c(0,0), legend.position=c(0,0)) 

對於其他位置你可以從這個文檔http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/

enter image description here

可能會嘗試,你會發現更好的解釋也在ab Ove鏈接。

+0

如果你仔細觀察傳說在左側不對齊,那就是OP的問題。 – zx8754

+0

@ zx8754我沒有完全理解你,這是否意味着傳說應該觸及左側的內部邊界? –

+0

@krishna:不幸的是,您的帖子無法解決我的問題,因爲我需要左右對齊兩個圖例。正如zx8754所寫,如果你仔細觀察,你可以看到它們仍然居中 - 只有傳說的位置已經改變。 zx8754已經解決了我的問題(請參閱上一篇文章)。無論如何,感謝您的嘗試! – Adela