formatting the x-axis with exponent values in R plot

I have generated this plot in R with some strange numbers formatting in the x-axis:

.

I want to have in the x-axis the numbers in the format (ax) as 2^6, 6^6, 10^6. This would simplify the x-axis to get data in all points.
Here is my code:

data=read.csv("my_file.csv",row.names = 1)
plot(genes~Prot,cex=1.5,data, function(x) 10^x, xlab="Proteome 
size(codons)",ylim=c(0,30), ylab="Genes in pathway")
abline(lm(prot~genes,data),lty=2, lwd=3,col="black")

Please any suggestions ?

Here is one way to set the x axis labels.

df <- data.frame(x = seq(1E6, 10E6, 1E6),
                 y = rnorm(10, 25, 6))
plot(y ~ x, data = df, xaxt = "n")
axis(1, at = seq(2E6, 10E6, 2E6), labels = c("2^6", "4^6", "6^6", "8^6", "10^6"))

Created on 2019-06-26 by the reprex package (v0.2.1)

That is called "scientific notation". And 2E6 is not 2^6, it's 2x10^6. How about this:

library(ggplot2)
library(scales)
library(ggthemes)

# data
set.seed(123)
df <- data.frame(genes = runif(20)*12e6+1e6,
                 Prot = runif(20)*20+5)

# formatting function
# https://stackoverflow.com/questions/10762287/how-can-i-format-axis-labels-with-exponents-with-ggplot2-and-scales
scientific <- function(x){
    ifelse(x==0, "0", parse(text=gsub("[+]", "", gsub("e", " %*% 10^", scientific_format()(x)))))
}

# plot
ggplot() +
    labs(x="Proteome size (codons)", y="Genes in pathway", title="A") +
    geom_point(data=df, mapping=aes(x=genes, y=Prot), size=3) +
    geom_abline(intercept=5, slope=1e-6, size=1.2) +
    theme_few() +
    scale_x_continuous(breaks=seq(2e6,12e6,2e6), label=scientific) +
    scale_y_continuous(limits=c(0,30))

Created on 2019-06-27 by the reprex package (v0.3.0)

2 Likes

Dear Woodward

Thanks a lot , you are right 2E6 is not 2^6. I really like your script, but it is with gig-lot. I would be happy to get my x-axis like your plot but just modifying my script. For what I want to do I would prefer to use plot instead of ggplot. Because what I show you here is just a part of my plot.

Thanks a lot do you think that I can set that using scientific notation instead of using what you propose ?

DD

I only used the 2^6 notation because you seemed to prefer that to the more standard 2E6 notation. You can adjust the labels to be whatever you want. For example

df <- data.frame(x = seq(1E6, 10E6, 1E6),
                 y = rnorm(10, 25, 6))
plot(y ~ x, data = df, xaxt = "n")
axis(1, at = seq(2E6, 10E6, 2E6), labels = c("2E6", "4E6", "6E6", "8E6", "10E6"))

Created on 2019-06-27 by the reprex package (v0.2.1)

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.