Search code examples
rggplot2

Accurately place legend in ggplot


I have below ggplot

library(ggplot2)
col_define = c('red', 'orange', 'blue', 'lightblue', 'green')
names(col_define) = as.vector(unique(diamonds$cut))

ggplot(diamonds, aes(color)) +
  geom_bar(aes(fill = cut)) +
  scale_fill_manual(values = col_define, breaks = names(col_define), aesthetics = c("fill")) + 
    theme(panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position=c(0,1),
        legend.justification = c(0,1),
        legend.box.margin = margin(5, l = 5, unit = 'mm'),
        legend.box = 'horizontal',
        legend.box.background = element_rect( fill = alpha('#7f7f7f', .2), size = 0.1, linetype = "solid", color = "#595959"),
        axis.text.x = element_text(angle = 30, hjust = 1)
        ) 

As you can see, the legend does not appear to be in the right position. I want to place my legend in top-left position within the plot area, but there will be top-margin and left-margin of 5 pixel.

Additionally, the margin color and alpha value also do not appear to be correctly visible. Also, legend items should be horizontally placed

Could you please help how to correct them?


Solution

  • Not 100% sure about your desired result. First, to place the keys horizontally you could use guide_legend(nrow = 1) (legend.box = 'horizontal' is for the arrangement of multiple legends not the legend keys or items). Second, concerning the background of the legend. Are you sure you want legend.box.background or legend.background instead?

    Concerning the placement of the legend everything looks fine to me except that using a numeric vector for legend.position was deprecated in ggplot2 3.5.0.

    library(ggplot2)
    col_define <- c("red", "orange", "blue", "lightblue", "green")
    names(col_define) <- as.vector(unique(diamonds$cut))
    
    ggplot(diamonds, aes(color)) +
      geom_bar(aes(fill = cut)) +
      scale_fill_manual(
        values = col_define,
        breaks = names(col_define), 
        guide = guide_legend(nrow = 1)
      ) +
      theme(
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(),
        legend.position = "inside",
        legend.position.inside = c(0, 1),
        legend.justification = c(0, 1),
        legend.box.margin = margin(5, l = 5, unit = "mm"),
        legend.background = element_rect(
          fill = alpha("#7f7f7f", .2), linewidth =  0.1,
          linetype = "solid", color = "#595959"
        ),
        axis.text.x = element_text(angle = 30, hjust = 1)
      )