当前位置:网站首页>Failed to save image in R language ggplot2 loop
Failed to save image in R language ggplot2 loop
2022-08-06 03:11:00 【I am a big pumpkin】
R语言ggplot2Failed to save image in loop
1.问题描述
在使用R语言ggplot2绘图时,Need to save multiple image results,所以使用循环.
结果,ggplot2when placed in a loop,If using Create Image(pdf("filename.pdf") 或 png("filename.png") etc...)and close the picture(dev.off())的命令,需要注意.
例如,使用下面的代码,Want to loop3个pdf图片文件(循环外,A single image operation is no problem),Use this in a loop不能保存图片且代码不报错.
require(ggplot2)
for(i in 1:3){
pdf(paste( i, ".pdf", sep=""))
ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length)) +
geom_point(aes(color=Species), size=3) +
scale_color_brewer(palette = "Set2")
dev.off()}
实际上生成的3个pdfThe file has no image content,In fact, the pictures in the cache are not released and saved toPDF中.
当然,如果不使用ggplot2也没这问题,也能正常保存
例如:
for(i in 1:3){
pdf(paste( i, ".pdf", sep=""))
plot(1:10)
dev.off()}
结果没问题:

2.问题解决
2.1 使用ggsave函数保存,成功
for(i in 1:3){
ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length)) +
geom_point(aes(color=Species), size=3) +
scale_color_brewer(palette = "Set2")
ggsave(paste( i, ".pdf", sep=""))}


2.2 使用print函数输出,成功
require(ggplot2)
for(i in 1:3){
pdf(paste( i, ".pdf", sep=""))
p1 <- ggplot(iris, aes(x=Sepal.Width, y=Sepal.Length)) +
geom_point(aes(color=Species), size=3) +
scale_color_brewer(palette = "Set2")
print(p1) ## 添加p1 print操作
dev.off()}


以上,使用ggplot2循环保存pdf时需要注意这一点,The file is successfully saved.
边栏推荐
- 【翻译】无服务器架构:利与弊
- Camera calibration > > coordinate system transformation @ inside and outside the cords
- Log Management Lombok Profile
- C Student Management System Print/Modify Designated Location Information
- KGAT recommendation system
- 二次开发入门须知
- 微信小程序 多选————四选二
- greenDAO of Android database framework
- js_array object is changed to be sorted (including parallel sorting)
- Entering the pit of machine learning: three, unsupervised learning
猜你喜欢
随机推荐
二次开发入门须知
什么浏览器广告少?多御安全浏览器轻体验
KGAT recommendation system
pcl point cloud networking vtk Delaunay point cloud networking
Entering the pit of machine learning: 2. Supervised learning
【翻译】无服务器架构:利与弊
NetCore——自定义全局异常处理
预处理(C语言深度了解)
MySQL -- 安装部署环境(一键安装脚本)
学习MySQL的第二天:SQL(基础篇)
Nine, MFC controls (1)
LeetCode Daily 2 Questions 01: Flip word prefixes (both 1200 questions)
NPDP为什么越来越受追捧?产品经理你可知道?
走!VR技术带你沉浸式看展
WeChat applet multi-select - four choose two
A complete solution for serial port data reception in QT
pytest之assert断言的使用
NRF52840-QIAA-R Nordic BLE5.0蓝牙无线收发芯片
Android数据库框架之greenDAO
Detailed description of hand-eye calibration (introduction of coordinate system, two-dimensional, three-dimensional hand-eye calibration method @ nine-point method, AX=XB)








