ssaz_5
ssaz_5

Reputation: 78

R: Axis tick labels Dynamic superscripting from an array

I am trying to generate axis ticks with superscripts in R for ggplot2. I want a plot similar to this: Plot from python

But the one I am able to make looks like this: Plot using ggplot2 R

Notice the axis ticks on y axis. The python one has 102, 104, 106 which I want to create with R but with my code I am unable to do so.

+scale_y_continuous(labels = function(x){return (paste("10^", x,sep = ""))})

I used this code to create the labels in the R plot. i.e. 10^2, 10^4, 10^6 etc. I tried using the function expression and all its variants that are available on different forums:

+scale_y_continuous(labels = function(x){return (expression(10^x))}

But all of them produced the same output which was 10x, 10x, 10x on all the ticks. Expression function does not understand the difference between a character and variable.

How exactly do I accomplish ticks like 102, 104, 106 without manually setting values for each tick. Since my code generates the tick labels using an array of values I can't manually do that. I am generating hundreds of plots at once so I need to do it dynamically by reading the y-axis values and converting them accordingly.

I do not want to change the formatting of the number. My array has already calculated log(x) values and I just want to add a 10 behind it and make it superscript. Changing the format using scientific_format is not the solution I am looking for as I want a method which can change the text to 102 form. I want to add labels without applying any changes to the data.

Upvotes: 2

Views: 565

Answers (1)

cuttlefish44
cuttlefish44

Reputation: 6776

I think scale_y_continuous(labels = math_format(10^.x)) is what you want:

library(scales); library(ggplot2)
a <- ggplot(iris, aes(x=Sepal.Length, y=Petal.Length)) + geom_point()   # Left (to compare)
b <- a + scale_y_continuous(labels = math_format(10^.x))   # Middle 
c <- b + annotation_logticks(side="l")                     # Right
   # (Note; "10^.x" is default value, so it is omissible.)
print(a); print(b); print(c)

enter image description here

Upvotes: 3

Related Questions