0

I've created a graph presenting data in linear units but in logarithmic y-scale (code below).

ggplot() + 
  geom_point(data=VH_lin, aes(x=VH_lin[,1], y=VH_lin[,2], colour = "green"), size=0.6) +
  scale_y_log10(breaks = c(0,0.01, 0.10, 1.00, 10), limit=c(-0.01,10)) + scale_x_continuous(breaks=c(0, 2000, 4000, 6000, 8000, 10000, 12000)) + 
  xlab("x") + ylab("y") +
  theme(panel.background = element_rect(fill = "white", colour = "grey50")) 

I would like to add second y scale in decibels - which are logarithmic units. To transform data I have to calculate 10*log10(x) so the distribution of data on the plot should be the same - as dB are logarithmic. Basically, I would like to present the dame data on the same plot using two units: linear (but presented in logarithmic scale - already in the code) and dB. Is it possible? The pic below (poorly) presents my idea.

enter image description here

Example of VH_lin data:

1 0 0.012729834
2 3.133577295 0.012729834
10 14.75257582 0.013739633
36 59.10725461 0.014644137
41 69.42152155 0.0103109
466 1180.242805 0.011991354
486 1204.63381 0.008985861
520 1256.814223 0.008706877
barbrka
  • 153
  • 1
  • 11
  • 1
    Have you looked at the [sec_axis](https://ggplot2.tidyverse.org/reference/sec_axis.html) help page? When asking for help, you should include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input that can be used to test and verify possible solutions. – MrFlick Jun 26 '18 at 18:24
  • I haven't looked at sec_axis before but it looks like what I do need. However, I can't figure out, how to apply 10*log10() transformation properly... I've edited my question and added some sample of data. – barbrka Jun 26 '18 at 19:09

2 Answers2

2

You can add the second axis while keeping data points in an original scale as follows:

ggData <- data.frame(x=rnorm(50), y=rnorm(50, mean=1000, sd=50) )
summary(ggData)

ggplot(ggData, aes(x=x, y=y) ) + 
 geom_point() + 
 scale_y_continuous(sec.axis = ~ 10*log10(.))
Lstat
  • 1,450
  • 1
  • 12
  • 18
  • Is it possible to do this without ggplot? (Sorry, I have a ton of legacy plot calls using the vanilla plot routines, which I am loath to switch over to ggplot. In the future, I should probably start with ggplot...) This would be useful, for example, plotting temperature which you could present the temp in F and C at the same time (or length in ft vs. cm, lbs vs. kgs, etc. Thanks – Clem Wang Oct 16 '18 at 22:55
0

If you want to add second y-axis in same scale with the prior one, it can be implemented like this: scale_y_log10(sec_axis = sec_axis(~.*, name="dB")

  • could you please also solve the problem of transformation of y values to 10*log10(y)? this is the main problem in this question but with the formula above I will not fix it. – barbrka Jun 27 '18 at 05:08