r - 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 .png”。
如果有人知道如何更改此图的标题、轴标签的名称等,这也会有所帮助。
解决方案
我认为原因是“find_droughts”函数的默认绘图是基于 dygraph 包的交互式绘图。
我可以想出两种方法来解决你的问题。
如果要绘制静态 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()
如果要绘制交互式绘图,可以执行以下操作:
# 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)
希望这可以帮助。
推荐阅读
- material-ui - Material UI 应用深色主题
- c - 将文件中的数字扫描到二维数组中
- json - POST 之前的 gzip JSON 有效负载
- python - 无法从 Python 正确解码 JSON URL
- javascript - 如何在 React 页面中只显示 pdf 第一页的屏幕截图?
- javascript - 如何按以下格式对包含时间的字符串数组进行排序?
- javascript - 根据错误状态更改元素的颜色代码
- json - xkcd api,如何阅读解释?
- android - Android Studio Manifest Merger 失败并出现多个错误
- php - 使用更改选择选项的新请求刷新页面