简体   繁体   中英

legend position and size in ggplot2

I have a some issue about legend position and legend box size problem in the ggplot2. I tried many things but no luck so far!

I don't want to put manual coordination to the legend box location and adjust its size depending on the plot for each time. I would like to have it always at a certain position with adjusted size when only needed!

I also want to remove 'white' filling in the background so I used

legend.key = element_blank()

but it seems it doesnt work too!

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

which creates this plot

在此处输入图片说明

What follows is not in my opinion a completely satisfying solution.
Using the solution proposed here we can add text using 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)

I hope it could help you.

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM