0

I'm trying to remove the margins around a plot from ggplot2. I'm working in a waffle context, so the reproducible example below is in this form.

I have followed the answers provided in Remove Plot Margins in ggplot2, but am still getting a strange result. I run the following code, and make the background of the plot yellow to highlight the margins.

library("waffle")

parts <- data.frame(
  names = LETTERS[1:4],
  vals = c(80, 30, 20, 10)
)

waffle(parts, rows = 8, xlab = "Each Square = X",legend_pos = "bottom") + 
  guides(fill = guide_legend(ncol=1))  +
  theme(plot.margin = margin(0,0,0,0,unit = "cm"),
        legend.margin = margin(b=0,unit="cm"),
        plot.background = element_rect(fill="yellow"))

ggsave(file = "graphs/test.jpg")

The following image is what I see when I paste the jpg into Word.

enter image description here

The yellow border confirms that the margins are correctly specified, but get the white border around the graph inside of the dashed line. Is there a way to avoid this?

Marcus Campbell
  • 2,746
  • 4
  • 22
  • 36
Bjørn Kallerud
  • 979
  • 8
  • 23
  • Set the image size with the `width` and `height` arguments of `ggsave` – camille Feb 06 '19 at 01:35
  • You can also use `knitr` to embed plots in `latex` which is a much cleaner work flow once you have it figured out. However there is a learning curve. – Prevost Feb 06 '19 at 01:57

1 Answers1

0

I was struggling with the same problem. In waffle function you can't change color of square boarders to transparent. But you can produce same waffle plot with ggplot2. Check code below:

library(tidyverse)

parts <- data.frame(
  names = LETTERS[1:4],
  vals = c(80, 30, 20, 10)
)

nrw = 8 # - number of rows
brd = .02 # - space between squares

parts %>%
  as_tibble() %>%
  transmute(sq = map2(names, vals, ~rep(.x, .y))) %>%
  unnest() %>%
  mutate(rn = row_number() %>% `/`(nrw) %>% ceiling()) %>%
  group_by(rn) %>%
  mutate(
    cn = row_number(),
    xmin = rn - .5 + brd,
    xmax = rn + .5 - brd,
    ymin = cn - .5 + brd,
    ymax = cn + .5 - brd
  ) %>%
  ggplot(aes(
    xmin = xmin,
    xmax = xmax,
    ymin = ymin,
    ymax = ymax,
    fill = sq
  )) +
  geom_rect() +
  coord_equal() +
  theme_void() +
  theme(plot.background = element_rect(fill = 'yellow'))

enter image description here

Paweł Chabros
  • 2,349
  • 1
  • 9
  • 12