rggplot2visualizationleftalign

How can I align the title and legend in the top left corner


ggplot(mtcars, aes(wt, qsec)) + 
  geom_point(
    aes(
       size = mpg
  )) + 
  labs(x = "", y = "", title = 'This is title', subtitle = 'This is subtitle') +
  guides(size = guide_legend(nrow = 1)) + 
  theme(
    panel.border = element_blank(),
    legend.position = 'top',
    legend.justification = 'left',
    plot.title = element_text(size = 18),
  )

enter image description here

I set both the title and legend to the top left corner, but it seems that they are not showing the top left corner in the same way. It feels like the title is in the top left corner of the entire image, but the legend is in the top left corner of the drawing area, so they are not aligned horizontally

Later I defined legend.position in themes(), but this would obscure the drawing area and not look good

enter image description here

ggplot(mtcars, aes(wt, qsec)) + 
  geom_point(
    aes(
       size = mpg
  )) + 
  labs(x = "", y = "", title = 'This is title', subtitle = 'This is subtitle') +
  guides(size = guide_legend(nrow = 1)) + 
  theme(
    panel.border = element_blank(),
    legend.position = c(-0.01,0.9),
    legend.justification = 'left',
    plot.title = element_text(size = 18),
  )

I hope you can help me


Solution

  • You can set legend.margin to have a negative left-hand side margin.

    library(tidyverse)
    
    ggplot(mtcars, aes(wt, qsec)) + 
      geom_point(
        aes(
          size = mpg
        )) + 
      labs(x = "", y = "", title = 'This is title', subtitle = 'This is subtitle') +
      guides(size = guide_legend(nrow = 1)) + 
      theme(
        panel.border = element_blank(),
        legend.position = 'top',
        legend.justification = 'left',
        legend.margin = margin(c(0, -1, 0, 0)),
        plot.title = element_text(size = 18),
      )
    

    Created on 2023-03-03 with reprex v2.0.2