Using ggplot sec.axis with non-monotonic transformation

I would like to use the option ggplot

sec.axis

to create a secondary X-axis (call it Z), showing the transformation Z = X + sqrt (X ^ 2 - X). This transformation is not monotonic at all, but monotonic in the X range, which is possible in my application (X> 1).

I tried the following:

x1 = seq(1, 3.5, .1)
y = rnorm( n = length(x1) )

d = data.frame( x1, y )

library(ggplot2)
ggplot( d, aes( x=x1, y=y ) ) + geom_point() +
  scale_x_continuous( sec.axis = sec_axis( ~ . + sqrt(.^2 - .) ) )

      

resulting in both an error and a warning:

Error in f(..., self = self) : 
  transformation for secondary axes must be monotonous
In addition: Warning message:
In sqrt(.^2 - .) : NaNs produced

      

They both suggest that it is trying to compute the value conversion with X <1, although this is not necessary for the plot.

How can I plot my monotonic transformation? I need a reasonably general solution, as this happens in a function for which the range of X is partially user-defined (but always> 1),

+3


source to share


2 answers


Well, you could trick ggplot into thinking it's monotonous:

f <- Vectorize(function(x) {
  if (x < 1) return(x/1e10)
  x + sqrt(x^2 - x)
})

ggplot( d, aes( x=x1, y=y ) ) + geom_point() +
scale_x_continuous(sec.axis = sec_axis(~f(.)))

      



Usage is expand = c(0, 0)

fine, but it shrinks the build area.

+3


source


This problem is caused by a space before the first x value. You can remove it using a parameter expand

.



ggplot(d, aes(x=x1, y=y) ) + 
 geom_point() +
 scale_x_continuous(
  expand = c(0, 0),  
  sec.axis = sec_axis( ~ . + sqrt(.^2 - .) ) 
 )

      

+2


source







All Articles