Skip to content

Instantly share code, notes, and snippets.

@csgillespie
Last active November 12, 2022 14:31
Show Gist options
  • Save csgillespie/eaa334e7455d3bb2fe967f5dc8614853 to your computer and use it in GitHub Desktop.
Save csgillespie/eaa334e7455d3bb2fe967f5dc8614853 to your computer and use it in GitHub Desktop.
Exploring R graphics
# Used in the blog post
# https://www.jumpingrivers.com/blog/r-graphics-cairo-png-pdf-saving/
library(ggplot2)
library(extrafont)
library(ragg)
library(Cairo)
extrafont::loadfonts()
set.seed(1)
x = rnorm(1000)
y = rnorm(1000)
get_plot = function(x, y) {
df = data.frame(x, y)
g = ggplot(df, aes(x = x, y = y)) +
geom_abline(intercept = 3, slope = 1, size = 3) +
geom_label(x = 2.5, y = -1,
label = "This is italic text\n in Arial Narrow",
family = "Arial Narrow",
fontface = "italic", size = 6, label.size = 0) +
theme_bw(base_family = "Times") +
theme(axis.title = element_text(face = "italic"),
plot.title = element_text( face = "bold"),
plot.subtitle = element_text(face = "italic"),
plot.caption = element_text(face = "plain"))
print(g + geom_point(alpha = 0.4))
}
get_plot(x, y)
dir.create("pdf-graphics", showWarnings = FALSE)
dir.create("png-graphics", showWarnings = FALSE)
## Lots of warnings
pdf("pdf-graphics/default.pdf")
get_plot(x, y)
dev.off()
Cairo::CairoPDF("pdf-graphics/CairoPDF.pdf")
get_plot(x, y)
dev.off()
grDevices::cairo_pdf("pdf-graphics/cairo_pdf.pdf")
get_plot(x, y)
dev.off()
### PNG device
res = 300
png("png-graphics/default.png",
width = 8 * res, height = 6 * res, res = res)
get_plot(x, y)
dev.off()
png("png-graphics/times-cairo.png", type = "cairo",
width = 8 * res, height = 6 * res, res = res)
get_plot(x, y)
dev.off()
png("png-graphics/times-cairo_png.png", type = "cairo-png",
width = 8 * res, height = 6 * res, res = res)
get_plot(x, y)
dev.off()
ragg::agg_png("png-graphics/times-ragg.png",
width = 8 * res, height = 6 * res, res = res)
get_plot(x, y)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment