1
votes

The plot below has the second x-axis with custom labels.

dat <- data.frame(f=seq(0.01,0.5,by=0.01),y=rnorm(50))
fPretty <- pretty(dat$f)
pPretty <- round(1 / fPretty, 2)

p1 <- ggplot(data=dat, aes(x=f,y=y))
p1 <- p1 + geom_line(color="red")
p1 <- p1 + labs(x = "Frequency")
p1 <- p1 + scale_x_continuous(expand = c(0,0),
                              sec.axis=sec_axis(~., breaks=fPretty,
                                                labels = pPretty,
                                                name="Period (1/f)"))
p1

I'd like to transform the x-axis to a log10 scale and plot the second axis to match:

p2 <- ggplot(data=dat, aes(x=f,y=y))
p2 <- p2 + geom_line(color="red")
p2 <- p2 + labs(x = "Frequency")
p2 <- p2 + scale_x_continuous(expand = c(0,0), trans="log10",
                              sec.axis=sec_axis(~., breaks=fPretty,
                                                labels = pPretty,
                                                name="Period (1/f)"))
p2

How can I set fPretty and pPretty in p2 to give the same effect?

I.e., in this case:

fPretty <- c(0.01, 0.1)
pPretty <- round(1 / fPretty, 2)

Do I use scales::log_breaks() and scales::trans_format()?

The aim is to specify custom tick marks for both x-axis's.

1
I agree. It's only an example with random data. - user111024
Also, I didn't understand your question, what :same effect" are you looking for? - Suren
Edited as per your suggestion. Thanks. - user111024
It is not clear what you mean by "the same effect". - Suren
In p1 I use fPretty <- pretty(dat$f) to calculate where the tick marks will be and use that for the second axis. How can I get fPretty for p2 which has the transformed axis? - user111024

1 Answers

0
votes

You have to specify tick location on the main x-axis and also the second one. That is add breaks in scale_x_continuous for the main x-axis.

For example,

fPretty <- c(0.01, 0.1)
pPretty <- round(1 / fPretty, 2)

p2 <- ggplot(data=dat, aes(x=f,y=y))
p2 <- p2 + geom_line(color="red")
p2 <- p2 + labs(x = "Frequency")
p2 <- p2 + scale_x_continuous(breaks = fPretty, 
                expand = c(0,0), trans="log10",
                sec.axis=sec_axis(~., breaks=fPretty,
                                      labels = pPretty,
                                       name="Period (1/f)"))
p2

enter image description here

EDIT Using fPretty and pPretty used in p1.

p2 <- p2 + scale_x_continuous(breaks = fPretty, expand = c(0,0), trans="log10", sec.axis=sec_axis(~., breaks=fPretty, labels = pPretty, name="Period (1/f)"))

enter image description here