ggplot2中的图例位置和大小

时间:2017-05-16 19:33:09

标签: r 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 个答案:

答案 0 :(得分:3)

以下内容在我看来并不是一个完全令人满意的解决方案 使用建议的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