R:如何使用代码将“ lfstat”包中“ find_droughts”函数的图另存为图像?

时间:2018-08-03 12:42:52

标签: r

当我尝试将这个特殊的图另存为图像时,我只会得到一个空白的白色图像文件。使用相同的代码,我设法保存了多个其他“正常”图,但是它对于find_droughts函数(也许对其他一些函数)也无效。

我可以通过单击查看器中的“导出”来手动保存图,但是我有很多图要保存,我真的很想使用代码来完成它。

此代码生成我想到的情节:

library(lfstat)

# random data
date<-seq(from=as.Date("2018-01-01"), to=as.Date("2018-12-31"), by="days")
flow<-c(runif(150, min=50, max=180),runif(95, min=25, max=50),runif(120, min=50, max=400))

# dataframe
flow.df<-data.frame(day(date),month(date),year(date),flow)
names(flow.df)<-c("day", "month", "year", "flow")
#dataframe to lfobj
lfobj <- createlfobj(flow.df,hyearstart = 1, baseflow = FALSE)
# lfobj to xts
flowunit(lfobj)<-"m^3/s"
xts<-as.xts(lfobj)

# find droughts
droughts<-find_droughts(xts, threshold=47, drop_minor = 0)

# Save plot as .png
savehere<-"C:/.../"
filename<-"myplot.png"
mypath <- file.path(paste(savehere,filename, sep = ""))
png(file=mypath)
plot(droughts)
dev.off()

我需要最后一步的帮助-“#将图另存为.png”。

如果有人知道更改此图的标题,轴标签名称等的方法,这也将有所帮助。

1 个答案:

答案 0 :(得分:1)

我认为原因是'find_droughts'函数的默认图是基于dygraph包的交互式图。

我可以想到两种方法来解决您的问题。

  1. 如果要绘制静态png,则可以在plot函数上定义绘图的类型,因此它不再是默认值(交互式)。根据您的代码,它将是:

    # Save plot as .png
    savehere <- "C:/.../"
    filename <- "myplot.png"
    mypath <- file.path(paste(savehere,filename, sep = ""))
    png(file=mypath)
    plot(droughts, type='l') # by defining type 'l', it will provide a plot of xts object, which is static
    dev.off()
    
  2. 如果要绘制交互式图,可以执行以下操作:

    # Save plot as .html
    library(htmlwidgets) # for saving html files
    savehere <- "C:/.../"
    filename <- "myplot.html"
    mypath <- file.path(paste(savehere,filename, sep = ""))
    InteractivePlot <- plot(droughts)
    saveWidget(InteractivePlot , file=mypath)
    # the above function will generate the interactive plot as an html file, but also a folder, which you might want to delete, since it's not required for viewing the plot. For deleting this folder you can do the following
    foldername <- "myplot_files"
    mypath <- file.path(paste(savehere,foldername , sep = ""))
    unlink(mypath, recursive = T)
    

希望这会有所帮助。