我需要在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
,以便我可以在plot2
和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(...)