如何将绘图封装在 R 中的函数中

问题描述 投票:0回答:1

我想将一个绘图封装在一个函数中,就像我在 ggplot 中所做的那样:

testGraphggplot <- function(data,x,y){
ggplot(data,aes(x={{x}},y={{y}}))+
geom_point()
}

testGraphggplot(cars,speed,dist)

如果我尝试这样做:

testGraphPlotly <- function(data,x,y){
plot_ly(data,x= ~{{x}},y=~{{y}}) %>% 
add_markers() %>% 
return()
}


testGraphPlotly(cars,speed,dist)

我收到错误“未找到对象‘速度’” 我尝试将 ~ 放在 x 和 y 之前,但没有任何变化。

r charts plotly
1个回答
0
投票

您可以在自己的自定义函数中使用

~
来创建一个具有如下情节的自定义函数:

library(plotly)

testGraphPlotly <- function(data,x,y){
  plot_ly(data,x= x,y=y) %>% 
    add_markers() %>% 
    return()
}


testGraphPlotly(cars,~speed,~dist)

创建于 2024-04-04,使用 reprex v2.0.2

© www.soinside.com 2019 - 2024. All rights reserved.