首页 > 解决方案 > R:如何使用代码将“lfstat”包中的“find_droughts”函数图保存为图像?

问题描述

当我尝试将此特定图保存为图像时,我只得到一个空白的图像文件。使用相同的代码,我设法保存了多个其他“正常”图,但它不适用于 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()

我需要最后一步的帮助 - “# Save plot as .p​​ng”。

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

标签: r

解决方案


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

我可以想出两种方法来解决你的问题。

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

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

希望这可以帮助。


推荐阅读