3

I want to have my x-axis show the scale with an added "m2" at the end of each axis text using the scales::label_number() function. Reproducible code:

tibble(x = 1:10, y = 1:10) |> 
ggplot(aes(x, y)) + 
scale_x_continuous(label = scales::label_number(suffix = "m^2"))

which gives me "5m^2" (for example) on the x-axis, whereas I want it to show "5m2". It seems the usual suspects of bquote() and expression() do not work with the scales::label_number() function.

2 Answers 2

3

Use unicode for ^2: "m\u00B2" or m^2: "\u33A1"

library(tibble)
library(ggplot2)

tibble(x = 1:10, y = 1:10) |>  
  ggplot(aes(x, y)) +  
  scale_x_continuous(label = scales::label_number(suffix = "m\u00B2"))

Created on 2022-05-16 by the reprex package (v2.0.1)

Sign up to request clarification or add additional context in comments.

1 Comment

I did not realise the ^2 was part of unicode :) Thank you
2

Using scales::label_parse you could do:

library(ggplot2)

data.frame(x = 1:10, y = 1:10) |>
  ggplot(aes(x, y)) +
  scale_x_continuous(
    label = ~ scales::label_parse()(
      paste0(scales::label_number()(.x), "*m^2"))
  )

2 Comments

Thank you very much! The above code seems to fail when the x-axis values are above 1000. This is because label_number() puts a gap between the "1" and "000". I found replacing the paste0(scales::label_number()(.x), "*m^2") with paste0(.x, "*m^2") overcomes this issue.
@FreddieJ.Heather. The code does not fail. label_number uses a space as grouping mark. And as you desired label_number ... (;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.