Home > Software design >  Adjusting position of colorbar tick labels in ggplot2
Adjusting position of colorbar tick labels in ggplot2

Time:06-29

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:

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='')

CodePudding user response:

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.

  • Related