-1

I have asked this question earlier but someone close it indicating that it has answer. I am pretty confuse how i can get the two variables plotted on two Y-axis. I want to plot Level on the left y-axis and Flow on the right y-axis (ie., secondary axis). Here is my data and i would appreciate a response.

library(tidyverse)
library(lubridate)

set.seed(1500)

FakeData <- data.frame(Date = seq(as.Date("2020-01-01"), to = as.Date("2020-01-31"), by = "days"),
                       Level = runif(31, 0, 30), Flow = runif(31, 1,10))
ggplot(data = FakeData, aes(x = Date))+
  geom(aes(y = Level))

Here is an example output of the plot i would like to see enter image description here

Hydro
  • 1,057
  • 12
  • 25
  • 1
    hi, I have no R access right now, but I think you are looking for the sec.axis argument ... have a look at this post (https://stackoverflow.com/questions/3099219/ggplot-with-2-y-axes-on-each-side-and-different-scales) I think it will answer your question :) – sambold Jun 25 '20 at 16:13
  • of course you would have to use different aes for geom_bar and geom_line (or whatever you are planning to use) – sambold Jun 25 '20 at 16:14

1 Answers1

2

Here is a start:

FakeData <- data.frame(Date = seq(as.Date("2020-01-01"), to = as.Date("2020-01-31"), by = "days"),
                       Level = runif(31, 0, 30), Flow = runif(31, 1,10))

scale_factor <- 4
   ggplot(data = FakeData, aes(x = Date))+
   geom_col(aes(y = Level), fill="darkgreen") +
   geom_line(aes(y = Flow*scale_factor), color="blue") +
   scale_y_continuous(sec.axis = sec_axis(~ .*1, labels = number_format(scale=1/scale_factor), name="Flow"))

enter image description here

Hydro
  • 1,057
  • 12
  • 25
Dave2e
  • 22,192
  • 18
  • 42
  • 50
  • Thanks @Dave, We are increasing `Flow` by a factor of 4- Can we bring it back to its original values? I tried `scale_y_continuous(sec.axis = sec_axis(~ .* scale_factor/4, name="Flow"))` - didn't work. – Hydro Jun 25 '20 at 18:47
  • @Hydro, Sorry, I needed to add the scale factor to the labels and not adjust the values, see the edit above. – Dave2e Jun 25 '20 at 19:02
  • Thanks @Dave, i guess we are duplicating some of the lines in your code. It does help solve my problem- I just need to play with the `secondary axis` `limits` now. any suggestion what to try to `limit` `seconcary axis` between certain `numbers`? – Hydro Jun 25 '20 at 19:12
  • I tried using `limits = c(0,10)` gives me a whole different scale. honestly, i didn't understand how the `sec-axis` formula works. – Hydro Jun 25 '20 at 19:22
  • The designers of ggplot have a philosophical dislike (being polite here) of a secondary axis with a different scale from the first. Thus why it is this difficult to get to work as desired. Since the secondary is scaled from the first, you can't set independent limits. You could add something like `breaks=scale_factor*seq(0, 10, 2)` to control where the tick marks and labels are. – Dave2e Jun 25 '20 at 19:47