使用R plot_ly在自定义函数中标题xaxis

时间:2017-02-22 00:39:08

标签: r function plotly axis-labels

我正在学习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]]”。

1 个答案:

答案 0 :(得分:0)

哎呀,我发帖太快了。解决方案很简单。

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')