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 to vertically align elements of legend box

I have below ggplot

library(ggplot2)
library(grid)
theme_set(theme_bw() +
  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'
        ))

ggplot(diamonds,aes(x,y,color=z))+
  geom_point()+
  scale_colour_gradient2('Time [min]',
                         low='lightgray',
                         mid='red3',
                         high='red4',
                         midpoint=15)

With this I am getting below plot,

enter image description here

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

However I wanted to horizontally align the colour definition in the legend, while colour title (i.e. Time [min]) should be on top of the colour definition. Is there any way to achieve this

>Solution :

By adding legend.direction = 'horizontal' and some guides,

ggplot(diamonds,aes(x,y,color=z))+
  geom_point()+
  scale_colour_gradient2('Time [min]',
                         low='lightgray',
                         mid='red3',
                         high='red4',
                         midpoint=15) + 
  theme_bw() +
  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.direction = 'horizontal'
  ) +
  guides(colour = guide_colourbar(title.position="top", title.hjust = 0.5),
         size = guide_legend(title.position="top", title.hjust = 0.5))

enter image description here

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