如何正确设置绘图循环?遇“opening device failed”报错求助
Hey there! Let's walk through why you're hitting that frustrating "opening device failed" error when trying to save your plots as PNGs, and fix it step by step.
Common Causes & Fixes
Let's break down the most likely issues in your code:
Incorrect Path Formatting (Windows-specific)
Windows uses backslashes (\) for file paths, but in R, backslashes are escape characters—meaning your path isn't being interpreted correctly. You have two easy fixes:- Use forward slashes (
/) instead:"C:/Users" - Double up the backslashes:
"C:\\Users"
- Use forward slashes (
Missing Username in Path
Your current path stops atC:/Users, but you need to include your actual user folder (e.g.,C:/Users/JohnDoe) to point to the right directory. Without this, R can't find where to save the file.Unclosed Graphics Devices
Every time you callpng(), you open a new graphics device. If you don't close it withdev.off()after plotting, you'll end up with too many open devices, which can trigger this error. Always adddev.off()at the end of each loop iteration.Potential Issues with the
namesList
IfPic1,Pic2, etc., are supposed to be string labels (not existing R objects), you need to wrap them in quotes. Using unquoted names will make R look for variables with those names, which might not exist and cause path errors when concatenated.
Corrected Code
Here's your code with all these fixes applied:
# Define names as string values (add quotes if these are labels, not objects) names <- c("Pic1", "Pic2", "Pic3", "Pic4", "Pic5", "Pic6", "Pic7", "Pic8", "Pic9", "P10") # Replace "YourUsername" with your actual Windows user folder name base_path <- "C:/Users/YourUsername" for (i in 1:10) { # Build the full file path correctly mypath <- file.path(base_path, paste0("myplot_", names[i], ".png")) # Print the path to verify it's correct (optional but helpful for debugging) print(mypath) # Open the PNG device png(file = mypath) # Create your plot mytitle <- paste("Training PIC", names[i]) par(mfrow = c(3,1), oma = c(2,2,4,2)) boxplot(ERRORS.train.pic[[i]], outline = FALSE, ylab = "RMSE(-)", xlab = "K-No") abline(h = 0, col = "red") # Add any other plot elements here... # Close the graphics device (critical!) dev.off() }
Extra Debugging Tips
- Run
print(mypath)inside the loop to check if the generated path is valid. Try navigating to that path manually in File Explorer to make sure the folder exists. - Ensure you have write permissions for the target folder. If you're saving to a restricted directory (like
C:/Program Files), you might need to run R as an administrator. - If you still get errors, try saving to a simpler path first (e.g.,
"C:/Temp") to rule out complex path issues.
内容的提问来源于stack exchange,提问作者Olli

