Last active
October 9, 2021 02:21
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
To make this work, I had to add
require( grid )
so that the call togrid.draw
would resolve.