问题描述
我有3个ggplots:简单点图,ACF,分位数-分位数图。我想编写一个具有某些功能的函数。默认情况下,它应该绘制所有三个图,但是它应该具有输入plot_types,在这里我可以指定应该绘制哪些图。所以我的函数应该有三个输入:第一个应该是向量,第二个应该绘制绘图,第三个是ACF中的最大滞后数(仅当我在第二个输入中指定ACF时,此变量才重要)。例如
visualise(rnorm(100),plot_types=c('dotplot','ACF'),lag_max=30) #it should plot only two graphs,simple dotplot and ACF with maximum
number of lags equals to 30.
visualise(runif(100),'qq-plot')) #it should plot dotplot and qqplot. Third input is not
needed because we do not need maximum number
of lags regarding to not specified ACF in input.
我的研究
#QQ plot
qqplot_data <- function(vec){
ggplot() + geom_qq(aes(sample = vec))+geom_abline()
}
#ACF
acf_plot<-function(vec,lag_max){
#calculate acf values
val_acf <- acf(vec,plot = FALSE,lag.max = lag_max)
#create data frame to use ggplot
df <- with(val_acf,data.frame(lag,acf))
#plot acf
ggplot(data = df,mapping = aes(x = lag,y = acf)) +
geom_hline(aes(yintercept = 0)) +
geom_segment(mapping = aes(xend = lag,yend = 0))+
scale_y_continuous(breaks=round(c(-1,-0.75,-0.5,-0.25,0.25,0.50,0.75),digits=2))
}
#Simple dotplot
dot_plot<-function(vec){
ggplot()+aes(x=1:length(vec),y=vec)+geom_point()
}
visualise<-function(vec,plot_types='all',lag_max){
#creating list of plots
plot.list<-list(dot_plot(vec),qqplot_data(vec),acf_plot(vec,lag_max))
#turning off appearance each of plot
show.plot <- c(FALSE,FALSE,FALSE)
#Turning on visualisation of all plots when plot_types is set to 'all'
if('all' %in% plot_types) {
show.plot <- c(TRUE,TRUE,TRUE)
} else {
#Turning on appearance of given plots specified in plot_types
if('dot_plot' %in% plot_types) show.plot[1] <- TRUE
if('qq_plot' %in% plot_types) show.plot[2] <- TRUE
if( 'ACF' %in% plot_types) show.plot[3] <- TRUE
}
plot_grid(plotlist = plot.list[show.plot])
}
#Examples
visualise(vec=rnorm(100),lag_max=30) #All plots
visualise(vec=rnorm(100),plot_types=c('ACF','dot_plot'),lag_max=30) #Plots ACF and dot_plot
问题是,当我尝试运行代码visualise(vec=rnorm(100),plot_types=c('dot_plot','qq_plot'))
时,我得到的信息是lag_max缺失,没有默认值,但是与在第二个输入中未指定ACF无关。我尝试解决此问题,当然可以通过在输入级别为lag_max指定某个值(例如visualise<-function(vec,plot_types,lag_max=20){...)
)来轻松完成,但是我正在寻找不默认包含lag_max的解决方案。您是否知道如何解决?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)