RDS 文件非常适合在 R 文件之间共享 R 对象。当我有一个特别复杂的布局时,我经常在 R 文件之间共享 ggplot 对象。通常这效果很好。
我的抱怨是,如果您的 ggplot() 函数调用包含全局变量,则当您将绘图保存为 .rds 文件时,该变量会丢失。因此,当您将绘图加载到新的 R 文件中时,这可不是好事。信息丢失。
有谁知道这个问题的巧妙解决方案?我想出的解决方法很笨拙。我真的不想回归到默认的 save() 和 load() 函数。
举几个例子怎么样。我将从一个有效的块开始。然后我将展示全局变量如何导致事情崩溃。
注意:此代码将在您当前的工作目录中放置一些垃圾文件。你们要被警告。
# Preliminaries -------------------------------------------
library(tibble)
library(magrittr)
library(ggplot2)
# Fake data
x <- 1:5 %>% as.factor()
y <- rnorm(5)
df <- data_frame(x, y)
# First an example that works -----------------------------
# Notice how the color palette is
# defined within scale_fill_manual()
this_plot_works <- ggplot(df, aes(x, y, fill = x)) +
geom_bar(stat = "identity") +
scale_fill_manual(values = c("red", "blue", …
Run Code Online (Sandbox Code Playgroud)