我是plot_ly软件包的新手,正在尝试生成一个在y轴上具有两个变量的时间序列线图。
在数据框“ baro”中,我具有POSIXct格式的“ DateTime”变量,以及数字格式的“ Pressure”和“ Temperature”。
我的代码基于此处给出的示例: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")
)
这将输出一组在x轴上标记为-1至6并在y轴上标记为-1至4的轴,而未绘制任何数据。
答案 0 :(得分:0)
我更喜欢使用管道%>%
,而不是将对象归因于绘图。
当您有2个Y轴时,最好明确设置每个Y轴的布局。
这应该做您想要的:
# 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"
)
)
在这里输出:
最诚挚的问候。