Home > Software design >  How to vertically align elements of legend box
How to vertically align elements of legend box

Time:06-09

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

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

CodePudding user response:

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

  • Related