You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于here包结合ggplot2的ggsave保存路径问题求助

Fixing 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 of here is 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 named Plots, not plots.
  • Ensure the Plots folder exists: While ggsave will throw an error if the folder doesn't exist, it's worth double-checking that you actually created ~/ProjFolder/Plots (not a typo like Plot or plots).

If you follow these steps, your plots should start showing up in the Plots subfolder instead of the project root!

内容的提问来源于stack exchange,提问作者EBrewe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 08:11:24