custom range on second y axis in ggplot (have already performed transformation)

Viewed 102

I am familiar with transforming my secondary y axis values in ggplot, however, I am unable to set a custom range for the min and max values. I would ultimately like to set the second y axis range values to a min of 40 and a max of 80. my first y variable has a range (0,108) and my second y variable has a range (47.44 - 71.17). In plot 1 we have a one to one transformation where I have the range going from a min of 0 to a max of 90. the code to produce this is

geom_line(aes(x=DATE, y = value/.75,colour= variable), size= 2)

and subsequently

scale_y_continuous(expand=c(0,0),
                     breaks = seq(0,120, by = 20),
                     label = comma,
                     sec.axis = sec_axis(~.*.75,
                                         breaks= seq(0,90,by=10),
                                         name = "Temperature (°F)"),
                     limits = c(0,120))

transformed second axes min 0 max 90

I have also tried this script to no avail

geom_line(aes(x=DATE, y = (value-40)/.75,colour= variable), size= 2)

and subsequently

  scale_y_continuous(expand=c(0,0),
                     breaks = seq(0,120, by = 20),
                     label = comma,
                     sec.axis = sec_axis(~.*.75+40,
                                         breaks= seq(40,80,by=10),
                                         name = "Temperature (°F)"),
                     limits = c(0,120))

which produces plot 2

transformed second axes min 40 to max 80

thanks in advance for any help with this

1 Answers

For future questions, please include something like this to reduce ambiguity and duplication of effort.

How to make a great R reproducible example

set.seed(0)
my_data <- tibble(DATE = seq.Date(as.Date("2020-01-01"), as.Date("2020-1-31"), by = "day"),
                  var1 = rpois(31, 5)^2,
                  var2 = runif(31, 40, 80))

Without transformation, this produces something like your example:

ggplot(my_data) +
  geom_col(aes(DATE, var1), fill = "gray70") +
  geom_line(aes(DATE, var2))

range(my_data$var1)  # 1 to 121
range(my_data$var2)  # 41 to 77

enter image description here

Let's say we want the 2nd axis to take up the whole scale range, so ~40 becomes 0 and ~80 becomes 120.

(var2 range - 40) * 3 = var1 range

We'll want to do the opposite translation for the axis itself:

(var2 scale / 3) + 40 = var1 scale

# transformed
ggplot(my_data) +
  geom_col(aes(DATE, var1), fill = "gray70") +
  geom_line(aes(DATE, (var2-40)*3)) +
  scale_y_continuous(sec.axis = ~(./3)+40)

enter image description here

Related