Last active
May 28, 2021 07:43
-
-
Save stmarcin/6b3177afa915eb02132c689e5a55c6b7 to your computer and use it in GitHub Desktop.
Remove white margins in the saved ggplot with no-white backround and coord_fixed() in #rstats
This file contains hidden or 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
library(ggplot2) | |
library(patchwork) | |
# example with coord_fixed() ------------------------------------------------------------------ | |
my_plot <- ggplot(data = iris, | |
aes(x = Sepal.Length, | |
y = Sepal.Width)) + | |
geom_point(color = "yellow") + | |
coord_fixed() + | |
theme_void() | |
fake_plot <- ggplot() + | |
theme_void() | |
layout <- " | |
AB | |
CC | |
" | |
my_plot + fake_plot + fake_plot + | |
plot_layout( | |
design = layout, | |
heights = c(1, 0.01), | |
widths = c(1, 0.01) | |
) + | |
plot_annotation( | |
title = "Plot with blue background and without white margins", | |
theme = theme( | |
plot.background = element_rect( | |
fill = "#002959", | |
color = NA), | |
plot.title = element_text(color = "yellow") | |
) | |
) | |
ggsave("plot.pdf", | |
width = 15, | |
height = 15, | |
units = "cm") | |
pdftools::pdf_convert(pdf = "plot.pdf", | |
filenames = "plot.png", | |
format = "png") | |
# example without coord_fixed ----------------------------------------------------------------- | |
ggplot(data = iris, | |
aes(x = Sepal.Length, | |
y = Sepal.Width)) + | |
geom_point(color = "yellow") + | |
labs( | |
title = "Plot with blue background and without white margins" | |
) + | |
coord_cartesian() + | |
theme_void() + | |
theme( | |
plot.background = element_rect( | |
fill = "#002959", | |
color = NA), | |
plot.title = element_text(color = "yellow") | |
) | |
ggsave("plot_2.pdf", | |
width = 15, | |
height = 15, | |
units = "cm") | |
pdftools::pdf_convert(pdf = "plot_2.pdf", | |
filenames = "plot_2.png", | |
format = "png") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment