在 R 中为 plotly 制作预定义布局

Making a predefined layout for plotly in R

我想制作一个预定义的布局,我可以将其用于我创建的绘图函数,以免每次制作绘图时都重复自己。例如,我尝试像下面那样做某事,但它不起作用并给出错误:

custom_layout <- function(){
  plotly::layout(
    xaxis = list(title = ""),
    yaxis = list(title = ""),
    title = list(text = title, y = 0.98)
  )
}

plot_bar <- function(title, dt, x, y, fill){
  plot_ly(dt, x =  ~x, y =  ~y, type = "bar",
          color =  ~ fill, split =  ~ fill) %>% 
    custom_layout()}

plot_line <- function(title, dt, x, y, fill){
  plot_ly(dt, x = ~x, y = ~y, type="scatter",
          split = ~fill, mode="lines+markers") %>% 
    custom_layout()}

我在我的代码中多次调用这 2 个绘图函数。我还有其他预定义的绘图功能,如 plot_lineplot_bar 我也为它们使用相同的布局但是现在手动添加如下布局:

plot_bar <- function(title, dt, x, y, fill){
  plot_ly(dt, x =  ~x, y =  ~y, type = "bar",
          color =  ~ fill, split =  ~ fill) %>% 
  layout(
    xaxis = list(title = ""),
    yaxis = list(title = ""),
    title = list(text = title, y = 0.98)

理想情况下,我想像在第一个场景中那样使用预定义布局来定义它,稍后我可以将其用于对我不起作用的每个绘图功能。有没有办法用原生 plotly 而不是 ggplot2 来做到这一点?

您需要使 custom_layout() 函数将 p 作为其第一个参数(就像 layout() 那样)。

library(tibble)
dt <- tibble(x=1:4, y=3:6, fill=1:4)

custom_layout <- function(p, title){
  plotly::layout(p,
                 xaxis = list(title = ""),
                 yaxis = list(title = ""),
                 title = list(text = title, y = 0.98)
  )
}

plot_bar <- function(title, dt, x, y, fill){
  plot_ly(dt, x =  ~x, y =  ~y, type = "bar",
          color =  ~ fill, split =  ~ fill) %>% 
    custom_layout(title=title)}


plot_bar(title="myplot", dt, "x", "y", "fill")