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"))

这创造了这个情节

在此处输入图片说明

马可·桑德里(Marco Sandri)

在我看来,以下内容并不是一个完全令人满意的解决方案。
使用此处提出的解决方案我们可以使用添加文本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)

希望对您有所帮助。

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章