【问题标题】:Title xaxis in custom function using R plot_ly使用 R plot_ly 在自定义函数中标题 xaxis
【发布时间】:2023-03-07 03:58:01
【问题描述】:

我正在学习 R。在 Maximilian Peters' answer 的帮助下,我编写了一个自定义函数来制作一堆散点图。我想用这些变量中的列名标记 x 和 y 轴标题。

代码如下:

library(plotly)
my_plot <- function(x, y, ...) {
  plot_ly(y = y, x = x, ...) %>%
    add_markers() %>%
    layout(xaxis = list(title = deparse(substitute(x))), 
           yaxis = list(title = deparse(substitute(y))))
}
my_plot(y = mtcars$mpg, x = mtcars$disp)

这会将 xaxis 标题设置为“x”,但我希望它是“disp”。

我也试过这个代码:

my_plot <- function(data, x, y, ...) {
  plot_ly(y = data[[y]], x = data[[x]], ...) %>%
    add_markers() %>%
    layout(xaxis = list(title = deparse(substitute(data[[x]]))), 
           yaxis = list(title = deparse(substitute(data[[y]]))))
}
my_plot(data = mtcars, y = 'mpg', x = 'disp')

这会将 xaxis 标题设置为“data[[x]]”。

【问题讨论】:

    标签: r function plotly axis-labels


    【解决方案1】:

    糟糕,我发布得太快了。解决方案很简单。

    my_plot <- function(data, x, y, ...) {
      plot_ly(y = data[[y]], x = data[[x]], ...) %>%
        add_markers() %>%
        layout(xaxis = list(title = x), 
               yaxis = list(title = y))
    }
    my_plot(data = mtcars, y = 'mpg', x = 'disp')
    

    【讨论】:

      猜你喜欢
      • 2017-07-09
      • 1970-01-01
      • 2018-07-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多