Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading