0

I am a newcomer to the plot_ly package and am trying to produce a time series line plot with two variables on the y axis.

In my dataframe 'baro' I have 'DateTime' variable in POSIXct format, and 'Pressure' and 'Temperature' in numeric format.

I am basing my code off the example given here: https://plot.ly/r/multiple-axes/

p <- plot_ly(baro)

add_trace(p, x = ~DateTime, y = ~Pressure, type = "scatter",
          mode = "lines", name = "Pressure")

add_trace(p, x = ~DateTime, y = ~Temperature, type = "scatter",
          mode = "lines", name = "Temperature", yaxis = "y2")

layout(p,
  title = "Pressure & Temperature", yaxis2 = ay,
  xaxis = list(title="x")
)

This outputs a set of axes labelled -1 to 6 on the x axis and -1 to 4 on the y axis with no data plotted.

2
  • Please share the output of dput(baro) in order for us to reproduce your problem. Commented Jul 9, 2019 at 16:35
  • 1
    You should have pipes ("%>%") between your functions. Maybe they didn't get pasted correctly in your question Commented Jul 9, 2019 at 19:39

1 Answer 1

1

I prefer use pipes %>% rather than attribute an object to a plot. When you have 2 Y-axis it's nice to set the layout of every one explicitly.

This should do what you want:

# Build randon data
set.seed(123)

baro = data.frame(DateTime = as.POSIXct(1:10,origin = "2019-01-01"),
                  Pressure = sample(1000:2000,10),
                  Temperature = sample(20:60,10)
                  )

# Build plot

baro %>%
  plot_ly(type = "scatter", mode = "lines") %>%
  add_trace(x = ~DateTime, y = ~Pressure, name = "Pressure")%>%
  add_trace(x = ~DateTime, y = ~Temperature, name = "Temperature", yaxis = "y2") %>%
  layout(title = "Pressure & Temperature",
         yaxis = list(title = "Pressure"),
         yaxis2 = list(title = "Temperature",
                       overlaying = "y",
                       side = "right"
                       )
         )

Here the output:

enter image description here

Best regards.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.