1
votes

I'm creating a chart in ggplot and want to change my x-axis ticks from scientific format to 10^n, 20^n, 30^n etc format without changing my axis to a log scale. I've copied code from the comments section in this thread:

How can I format axis labels with exponents with ggplot2 and scales?

And slightly altered it to this:

scale_x_continuous(label= function(x) {ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", "^", scientific_format()(x)))))} )

This gives me tick axis labels in the form 1^n, 2^n, 3^n etc. Is there any way to change this to 10^n, 20^n, 30^n etc (n-1 obviously)?

Many thanks.

2

2 Answers

0
votes

Does this meet your needs?

library(scales)
library(ggplot2)
library(stringr)
library(magrittr)

my_format <- function(x){
  g <- scientific_format()(x) %>% 
    stringr::str_split("e\\+") %>% 
    unlist() %>% 
    as.numeric()
  paste0(g[1], "0^", g[2]-1)
}

ggplot(dd, aes(x, y)) + 
  geom_point()+
  scale_x_continuous(label= function(x) {
    ifelse(x==0, 
           "0", 
           parse(text = my_format(x))
           )
    } )
0
votes

After fiddling around with the code a bit more, I came up with this solution:

scale_x_continuous(label= function(x) {ifelse(x==0, "0", parse(text=gsub("[+]","",gsub("e","0^4",gsub("05","",scientific_format()(x))))))} )

My x axis tick values were formatted as 0, 1^5, 2^5 and 3^5. The code adds a zero to after the first number and replaces "5" with "4" so that now I get 0, 10^4, 20^4 and 30^4 as my x axis tick values.

Hope this helps people! It should be possible to adapt the code to whatever power value required.