I have an R script that produces several graphics, I run into this problem that with at least some of these graphics, when I source the script the pdf file that is supposed to have the graphic has no pages. However when I run the file from the beginning simply running every line, I get the desired graph. I do not understand the problem and I couldn't find someone with precisely the same problem upon searching.
My code outputting the graphic in question (which is not the first graphic produced by the script) is roughly as follows:
library(ggplot2)
container$C <- as.factor(container$C)
pdf("../dataVis/AC.pdf")
p <- ggplot(container, aes(x = A*1000)) +
geom_histogram(aes(fill = C), bins = 24) +
xlab("A") +
ylab("Frequency") +
theme(legend.text = element_text(size = 18), axis.title = element_text(size = 18),
legend.title = element_text(size = 18), axis.text = element_text(size = 18)) +
xlim(c(0, 2.5))
p$labels$fill <- "C"
p
dev.off()
Here's the session info after sourcing the file in question:
R version 4.0.0 (2020-04-24)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19043)
Matrix products: default
locale:
[1] LC_COLLATE=English_Canada.1252 LC_CTYPE=English_Canada.1252 LC_MONETARY=English_Canada.1252
[4] LC_NUMERIC=C LC_TIME=English_Canada.1252
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] ggplot2_3.3.5
loaded via a namespace (and not attached):
[1] rstudioapi_0.13 magrittr_2.0.2 tidyselect_1.1.2 munsell_0.5.0 mise_0.1.0
[6] colorspace_1.4-1 R6_2.5.1 rlang_1.0.1 fansi_1.0.2 dplyr_1.0.8
[11] tools_4.0.0 grid_4.0.0 data.table_1.13.0 gtable_0.3.0 utf8_1.2.2
[16] cli_3.2.0 DBI_1.1.2 withr_2.4.3 ellipsis_0.3.2 matrixStats_0.57.0
[21] digest_0.6.29 assertthat_0.2.1 tibble_3.1.6 lifecycle_1.0.1 crayon_1.5.0
[26] farver_2.1.0 purrr_0.3.4 vctrs_0.3.8 glue_1.6.1 labeling_0.4.2
[31] compiler_4.0.0 pillar_1.7.0 generics_0.1.2 scales_1.1.1 pkgconfig_2.0.3
My only hypothesis is that it is something to do with how source() is handled by R that prevents this graphic from being produced correctly, and possibly that it has something to do with ggplot2. I am honestly not sure how to approach a problem that only shows up when I source and not when I run the script.