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.
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:
Best regards.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.