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

Adjusting position of colorbar tick labels in ggplot2

I’m trying to slightly reposition the labels of a discrete colorbar so that they don’t overlap, without changing the values of the breaks themselves. In the below plot, the two center labels (bracketing the near-zero data) are too close together, so that it looks like ‘-11’ instead of ‘-1’ and ‘1’. I’d like to nudge them to either side, or change the justification of each half of the scale (left justify the negatives and right justify the positives), or anything to create more space between the labels while retaining the spacing of the actual colorbar. (Making the colorbar wider is not an option in my actual figure.)

example figure

Here is the code used to create this plot:

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

library(dplyr)
library(ggplot2)
library(scales)

df <- data.frame(
  x = runif(1000),
  y = runif(1000),
  z1 = rnorm(100)*10
)

df %>% ggplot() + 
  geom_point(aes(x=x,y=y, color=z1)) + 
  scale_color_steps2(low = muted("darkblue"), mid = "white", high = muted("darkred"), 
                     midpoint = 0, guide_colorbar(barwidth = 20),
                     breaks = c(-20, -10, -5, -1, 1, 5, 10, 20)) + 
  theme_minimal() + 
  theme(legend.position = 'bottom') +
  labs(x='', y='', color='')

>Solution :

Always a bit hacky and you get a warning but one option would be to pass a vector to hjust argument of element_text to align the -1 to the right and the 1 to the left:

library(ggplot2)

set.seed(123)

df <- data.frame(
  x = runif(1000),
  y = runif(1000),
  z1 = rnorm(100)*10
)

ggplot(df) + 
  geom_point(aes(x=x,y=y, color=z1)) + 
  scale_color_steps2(low = scales::muted("darkblue"), mid = "white", high = scales::muted("darkred"), 
                     midpoint = 0, guide = guide_colorbar(barwidth = 20),# horizontal_legend,
                     breaks = c(-20, -10, -5, -1, 1, 5, 10, 20)) + 
  theme_minimal() + 
  theme(legend.position = 'bottom') +
  labs(x='', y='', color='') +
  theme(legend.text = element_text(hjust = c(rep(.5, 3), 1, 0, rep(.5, 3))))
#> Warning: Vectorized input to `element_text()` is not officially supported.
#> Results may be unexpected or may change in future versions of ggplot2.

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