Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active October 9, 2021 02:21
Show Gist options
  • Save primaryobjects/700fe43b9631412fe0e1 to your computer and use it in GitHub Desktop.
Save primaryobjects/700fe43b9631412fe0e1 to your computer and use it in GitHub Desktop.
Add text outside the chart area of a ggplot2 graph in R and save the resulting chart to a png file.
require(ggplot2)
require(gridExtra)
saveChart <- function(chart, fileName) {
# Draw attribution.
chart <- chart + geom_text(aes(label = 'sentimentview.com', x = 2.5, y = 0), hjust = -2, vjust = 6, color="#a0a0a0", size=3.5)
# Disable clip-area.
gt <- ggplot_gtable(ggplot_build(chart))
gt$layout$clip[gt$layout$name == "panel"] <- "off"
grid.draw(gt)
# Save chart.
ggsave <- ggplot2::ggsave; body(ggsave) <- body(ggplot2::ggsave)[-2]
chart <- arrangeGrob(gt)
ggsave(fileName, chart)
}
data <- data.frame(name = c('Company A', 'Company B', 'Company C', 'Company D'), age = sample(1:4))
g <- ggplot(data=data, aes(x=name, y=age)) + xlab("Company") + ylab('Years') + ggtitle('Something Nifty') + geom_bar(stat='identity') + theme_bw()
saveChart(g, "chart.png")
@aourednik
Copy link

I get:
Error in dev(file = filename, width = dim[1], height = dim[2], ...) : could not find function "dev"
my packages : ggplot2 2.2.1, grid 3.4.2, gridExtra 2.3, ggthemes 3.4.0
R implementation:
platform x86_64-pc-linux-gnu
svn rev 73368
version.string R version 3.4.2 (2017-09-28)

@carljparker
Copy link

To make this work, I had to add require( grid ) so that the call to grid.draw would resolve.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment