我必须在 R 中创建一系列图并plotly
为此使用。它们中的很多具有相同的轴,我想复制layout
绘图的一部分而不必明确地编写它。有没有办法做到这一点?
代码
数据
dat <- data.frame(time = seq.POSIXt(from = Sys.time(), to = Sys.time() - weeks(4),
length.out = 720),
output = rnorm(720, mean = 4000, sd = 300),
temperature = rnorm(720, mean = 25, sd = 4))
三地块:
plot1 <- plot_ly(dat) %>%
add_trace(x = ~time, y = ~output, name = 'Output', mode = 'lines+markers',
type = 'scatter') %>%
layout(
axis = list(title = 'Time'),
yaxis = list(title = 'Power Output (kW)'),
plot_bgcolor = '#EDEDED'
)
plot2 <- plot_ly(dat) %>%
add_trace(x = ~time, y = ~output, name = 'Output', mode = 'lines+markers',
type = 'scatter') %>%
add_trace(x = ~time, y = ~temperature, name = 'Temperature', mode = 'lines+markers',
type = 'scatter') %>%
layout(
axis = list(title = 'Time'),
yaxis = list(title = 'Power Output (kW)'),
yaxis2 = list(title = 'Temperature (C)', overlaying = 'y', side = 'right'),
plot_bgcolor = '#EDEDED'
)
plot3 <- plot_ly(dat[output > 3500, ]) %>%
add_trace(x = ~time, y = ~output, name = 'Output', mode = 'lines+markers',
type = 'scatter') %>%
add_trace(x = ~time, y = ~temperature, name = 'Temperature', mode = 'lines+markers',
type = 'scatter') %>%
layout(
axis = list(title = 'Time'),
yaxis = list(title = 'Power Output (kW)'),
yaxis2 = list(title = 'Temperature (C)', overlaying = 'y', side = 'right'),
plot_bgcolor = '#EDEDED'
)
有没有办法定义一个layout
我可以重用的 if forplot2
和plot3
. 就像是:
twoAxis <- list(
axis = list(title = 'Time'),
yaxis = list(title = 'Power Output (kW)'),
yaxis2 = list(title = 'Temperature (C)', overlaying = 'y', side = 'right'),
plot_bgcolor = '#EDEDED'
)
在情节中调用它:
plot2 <- plot_ly(dat, layout = twoAxis) %>%
add_trace(...) %>%
add_trace(...)
layout
使用一些默认参数值围绕函数编写包装器可能是有意义的。这样,您仍然可以在必要时灵活地指定不同或额外的输入参数:
library(plotly)
## define wrapper function around `layout`
twoAxisLayout <- function(p,
xaxis = list(title = "Time"),
yaxis = list(title = "Power Output (kW)"),
yaxis2 = list(title = 'Temperature (C)', overlaying = 'y', side = 'right'),
plot_bgcolor = '#EDEDED', ...) {
layout(p, xaxis = xaxis, yaxis = yaxis, yaxis2 = yaxis2, plot_bgcolor = plot_bgcolor, ...)
}
## use template layout function
plot2 <- plot_ly(dat) %>%
add_trace(x = ~time, y = ~output, name = 'Output', mode = 'lines+markers',
type = 'scatter') %>%
add_trace(x = ~time, y = ~temperature, name = 'Temperature', mode = 'lines+markers',
type = 'scatter') %>%
twoAxisLayout()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句