Home > Software design >  ggplot negative sign in continues color scale does not align in center of text
ggplot negative sign in continues color scale does not align in center of text

Time:01-20

So I was making a plot with ggplot2 and to remove as much white-space as possible, I removed the spacing between the legend key and legend text. To my surprise the - sign did not align in the center of the text and makes it look like the text is miss aligned with the ticks on the color legend.

Are there any hacks that can properly align the - sign? It looks quite ugly to me as it is with the - sign almost aligned where the . is for indicating decimal.

Edit: Noteworthy, I am looking for a programmatic solution where breaks/labels/values does not need to be set manually each time.

MWE:

library(tibble)
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.2
set.seed(1)
tibble(
  y = 1:10,
  x = 1:10,
  c = -runif(10)
) %>% 
  ggplot(aes(x, y, color = c))  
  geom_point()  
  theme(
    legend.position = c(.5, .5),
    legend.text = element_text(size = 12),
    legend.spacing.x = unit(.1, 'pt')
  )

Created on 2023-01-19 with reprex v2.0.2

CodePudding user response:

You could substitute the default minus sign using the arithmetic minus sign (unicode 2212). This can be done via a little lambda function passed to the labels argument of scale_color_continuous

library(tibble)
library(ggplot2)

set.seed(1)
tibble(
  y = 1:10,
  x = 1:10,
  c = -runif(10)
) %>% 
  ggplot(aes(x, y, color = c))  
  geom_point()  
  scale_color_continuous(labels = ~paste(ifelse(sign(.x) == -1, "\u2212", ""),
                                         sprintf("%2.2f", abs(.x))))  
  theme(
    legend.position = c(.5, .5),
    legend.text = element_text(size = 12),
    legend.spacing.x = unit(.1, 'pt')
  )

Created on 2023-01-19 with reprex v2.0.2

  • Related