2017-05-16 184 views
2

我有一個關於ggplot2中的圖例位置和圖例框大小問題的問題。我嘗試了很多東西,但到目前爲止沒有運氣!ggplot2中的圖例位置和大小

我不想對圖例框位置進行手動協調,並根據每次繪圖調整其大小。我希望在需要的時候始終在一定的位置調節尺寸!

我也想刪除「白」的背景填充,所以我用

legend.key = element_blank() 

但似乎它不工作了!

library(ggplot2) 

ggplot(diamonds, aes(x = carat, y = price, color = cut)) + 
    geom_point() + 
    labs(title = "Scatterplot", x = "Carat", y = "Price") + # add axis labels and plot title. print(gg) 
    facet_wrap(color ~ cut) + 
    theme(legend.position = c(0.9, 0.8), 
      legend.title = element_text(colour = "black", size = 6, face = "bold"), 
      legend.text = element_text(colour = "black", size = 6), 
      legend.key = element_blank(), 
    ) + 
    guides(col = guide_legend(override.aes = list(size = 1, alpha = 1), 
           nrow = 1, title.position = "left")) 

它創建該地塊

enter image description here

+1

嘗試'legend.position = 「頂」,legend.justification = 「右」' – Henrik

+0

如果只是用'facet_grid',而不是'facet_wrap',它更顯然是多餘。 – alistaire

+0

@亨利克謝謝你!但那時標題'Scatterplot'移到了左上角位置。我希望他們在同一行中!這縮小了總體情節! – Alexander

回答

2

接下來是不是在我看來完全令人滿意的解決方案。
利用該解決方案提出here我們可以使用grid.text添加文字:

library(ggplot2) 

p <- ggplot(diamonds, aes(x = carat, y = price, color = cut)) + 
    geom_point() + 
    labs(x = "Carat", y = "Price") + # add axis labels and plot title. print(gg) 
    facet_wrap(color ~ cut) + 
    theme(legend.position = c(0.9, 0.8), 
      legend.title = element_text(colour = "black", size = 6, face = "bold"), 
      legend.text = element_text(colour = "black", size = 6), 
      legend.key = element_blank(), 
    ) 

makeTitle <- function(txt, xpos, ypos, size=1, color= "black") { 
    require(grid) 
    pushViewport(viewport()) 
    grid.text(label = txt, 
    x = unit(xpos,"npc"), 
    y = unit(ypos, "npc"), 
    just = c("left", "bottom"), 
    gp = gpar(cex = size, col = color)) 
popViewport() 
} 

p + guides(col = guide_legend(override.aes = list(size = 1, alpha = 1), 
           nrow = 1, title.position = "left")) + 
theme(legend.position = "top", legend.justification = "right") 

makeTitle("Scatterplot", size=1.5, xpos=0.05, ypos=0.95) 

我希望它可以幫助你。

enter image description here

+0

嗨,感謝您爲解決此問題所做的努力。似乎沒有簡單的方法來解決這個問題。謝謝! – Alexander