1

Suppose I have

y <- 10:15
x <- 1:6
ggplot()+geom_line(aes(x = x,y = y))+scale_y_continuous(limits = c(min(y),max(y)),sec.axis = sec_axis(trans = ~. )

I want a transformation on the secondary axis that gives me values from 0 to 1. That is, getting the y value, subtract min (y) and then divide the resulting number by (max (y) - min (y).

The problem is, I have to get the number, subtract min (y), and then I have to transform again. I can't do this. If I try trans = ~.-min(y)/(max(y)-min(y)), I don't get what I want. How can I make it understand (yvalue - min y) is my new value, and then divide it?

M--
  • 25,431
  • 8
  • 61
  • 93
Luan Vieira
  • 117
  • 1
  • 10
  • Duplicate of [ggplot with 2 y axes on each side and different scales](https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) – M-- Sep 23 '19 at 14:57

1 Answers1

2

You can wrap your calculation steps in a temporary function:

y <- 10:15
x <- 1:6

my_fun <- function(y) {
  (y - min(y)) / (max(y)-min(y))
}

ggplot() +
  geom_line(aes(x = x,y = y)) +
  scale_y_continuous(limits = c(min(y),
                                max(y)),
                     sec.axis = sec_axis(trans = ~ my_fun(.) ))
haci
  • 241
  • 1
  • 8