R语言调用dev.off()报错:无法关闭设备1(空设备)求助
Hey there, fellow R newbie! I’ve run into this exact dev.off() headache before, so let’s break down what’s going on and how to fix it.
First, that error usually pops up when R gets confused about which graphics device is active—either the PDF device you tried to open wasn’t properly initialized, or there are leftover devices running in the background from previous code runs. Even restarting RStudio might not always clear these up completely!
Here are a few tried-and-true solutions to get your plots saving correctly:
1. Clear all active devices first
Before running your plotting code, force-close every open graphics device to start fresh. Run this line:
while (!is.null(dev.list())) dev.off()
This loop will keep closing devices until only the null device (device 1) is left. Then try your original code again:
pdf("spec_accum_w_sample.pdf") plot(specaccum(counts)) dev.off()
2. Explicitly target the PDF device
Sometimes R might silently switch back to the RStudio Plots pane device without you noticing. To avoid this, explicitly track and target the PDF device:
# Open the PDF device and store its ID pdf_dev <- pdf("spec_accum_w_sample.pdf") # Make sure the PDF device is the active one dev.set(pdf_dev) # Plot your graph plot(specaccum(counts)) # Close the specific PDF device dev.off(pdf_dev)
3. Try a more robust PDF driver
The default pdf() function can be finicky on some systems. Give cairo_pdf() a shot—it’s more reliable for many setups:
cairo_pdf("spec_accum_w_sample.pdf") plot(specaccum(counts)) dev.off()
4. Tweak RStudio’s graphics settings
If the above fixes don’t stick, adjust RStudio’s default graphics device to avoid conflicts:
- Go to Tools > Global Options > Graphics
- Change the "Graphics device" dropdown from "Auto" to "PNG" (or another non-PDF option)
- Restart RStudio and try your code again
One quick check: Even if you see the error, double-check the generated PDF file—sometimes the plot still gets saved despite the warning! But these steps should eliminate the error entirely.
内容的提问来源于stack exchange,提问作者Angelina

