关于here包结合ggplot2的ggsave保存路径问题求助
ggsave + here Package Path Issues Hey there! Let's get your plots saving into the Plots subfolder like you want—this is a common gotcha with the here package, but easy to fix once you know the right pattern.
First, let's recap how the here package works: it anchors all paths to your RStudio project's root directory (the folder where your .Rproj file lives). The key mistake here is probably that you're not explicitly telling ggsave to use the Plots path generated by here.
Step 1: Confirm your project root is correctly identified
First, double-check that here knows where your project root is. Run this in your console:
here::dr_here()
This will print the folder here is using as your root, plus a short explanation of how it found it. It should point directly to ~/ProjFolder—if not, make sure you've actually opened the .Rproj file (not just opened an R script in that folder) to activate the project context.
Step 2: Correctly use here with ggsave
There are two reliable ways to save your plot to the Plots folder:
Method 1: Use the path argument in ggsave
Pass the Plots path generated by here to the path parameter of ggsave:
library(ggplot2) library(here) # Example plot my_plot <- ggplot(mtcars, aes(mpg, hp)) + geom_point() # Save to Plots folder ggsave( filename = "my_car_plot.png", plot = my_plot, path = here("Plots") # This tells ggsave to use the Plots subfolder )
Method 2: Build the full file path with here
Alternatively, you can construct the complete file path directly using here, and pass that to the filename argument:
ggsave( filename = here("Plots", "my_car_plot.png"), plot = my_plot )
This is my preferred method because it makes the full save path explicit in your code.
Common Pitfalls to Avoid
- Don't use absolute paths: Avoid writing something like
~/ProjFolder/Plots/my_plot.png—the whole point ofhereis to handle path differences across operating systems automatically. - Check folder name case: If you're on macOS or Linux, folder names are case-sensitive. Make sure your code uses
here("Plots")(capital P) if your folder is namedPlots, notplots. - Ensure the
Plotsfolder exists: Whileggsavewill throw an error if the folder doesn't exist, it's worth double-checking that you actually created~/ProjFolder/Plots(not a typo likePlotorplots).
If you follow these steps, your plots should start showing up in the Plots subfolder instead of the project root!
内容的提问来源于stack exchange,提问作者EBrewe

