Here's the imgcat docs, which links to the actual imgcat script, but if you install iTerm2 (and maybe its shell integration; Menu > iTerm2 > Install Shell Ingegration) it should be at ~/.iterm2/imgcat, so the function from above should do the trick (for ggplot; for other graphics set up a similar print method):
print.ggplot <- function(x, width = 6, height = 4, dpi = 100, ...){
path <- tempfile(fileext = '.png')
ggplot2::ggsave(filename = path, plot = x,
width = width, height = height, dpi = dpi, ...)
system(paste('~/.iterm2/imgcat', path))
file.remove(path)
}
You could put that in your .Rprofile, but I wouldn't recommend it if you plan to use R with any other graphics device. An alternative is to define an explicit printing function, e.g.
imgcat <- function(x, ...){
path <- tempfile(fileext = '.png')
png(path, ...)
x
dev.off()
system(paste('~/.iterm2/imgcat', path))
file.remove(path)
}
which you can pass an expression to print, e.g.
imgcat(plot(1))
or
imgcat({
palette(rainbow(2, s = .5, v = 0.6))
stars(cbind(1:16, 10 * (16:1)), draw.segments = TRUE)
}, height = 300)
(h/t Yihui)
so