많은 비슷한 플롯의 생성을 표준화하기 위해 ggplot2로 플롯을 작성하려고합니다. theme(), stat _ *() 또는 geom _ *()을 + 연산자와 함께 사용하여 여러 옵션을 쌓을 수 있다면이 함수를 어떻게 감쌀 수 있습니까?ggplot2, 어떻게 함수 내에서 데이터 프레임 요소에 액세스합니까?
내가 예를 들어, 데이터 프레임의 부분을 플롯하는 함수를 작성하고 싶습니다은 :
library(ggplot2)
test<-function(fdata,fx){
p<-ggplot(fdata,aes(x=fx,y=mpg))+geom_point()
print(p)};
test(mtcars,wt)
은의 오류 반환 :
Error in eval(expr, envir, enclos) : object 'fx' not found
을하지만, 로컬에 미적 정의를 변경 범위가 지정된 변수 (예 : x = fx에서 x = wt)는 작동하지만 함수의 두 번째 옵션 인 'fx'는 사용하지 않습니다.
library(ggplot2)
test<-function(fdata,fx){
p<-ggplot(fdata,aes(x=wt,y=mpg))+geom_point()
print(p)};
test(mtcars,wt)
데이터 프레임의 다른 변수로부터 플롯을 생성하는 함수를 작성하려면 어떻게해야합니까?
예. 대신 aes
를 사용하는 aes_string
를 사용하는
test(mtcars,'wt') #scatter plot of wt x mpg
test(mtcars,'disp') #scatter plot of disp x mpg
test(mtcars,'hp') #scatter plot of hp x mpg