27

I'm trying to produce a png chart using ggplot2 and ggsave (with Cairo) in R. I'm having an issue with customising the theme to remove margins.

Currently I'm using:

... + theme(plot.margin=unit(c(0,0,0,0),"mm"))      

This seems to work for two out of four sides of my plot, it removes the top and right hand side margin completely, but there is still a fairly large margin on the left and bottom sides. Is there a way to completely remove these? Image below to illustrate the problem:

enter image description here

If a reproducible example would be useful then let me know and I'll put one together.


Edit:

library("ggplot2")
library("scales")
library("Cairo")
library("grid")

# Set chart values
line.width = 0.45
axis.font.size = 2.9

# Generate some random data
start.date <- as.Date("2011-07-01")
x.month <-seq.Date(start.date, by = "month", length.out = 24)
end.date <- max(x.month)

period.a <- rnorm(12, mean=50, sd=2)
period.b <- rnorm(12, mean=55, sd=2)

x.value <- c(period.a,period.b)

# Combine into dataframe
x.data <- data.frame(
  "Month" = x.month,
  "Value" = x.value
  )

# Build chart
p <- ggplot(data=x.data, aes(Month, Value)) + geom_line(size=line.width)
p <- p + theme_bw()
p <- p + scale_y_continuous()
p <- p + scale_x_date(limits=c(start.date+20,end.date-20), breaks = "1 month",labels = date_format("%b-%y"))
p <- p + theme(axis.text.x=element_text(angle=90, hjust=1, vjust=0.5, size=axis.font.size),
                axis.text.y=element_text(size=axis.font.size),
                axis.title.x=element_blank(),
                axis.title.y=element_blank(),
                plot.margin=unit(c(0,0,0,0),"mm"),
                plot.background = element_rect(fill = "grey"),
                panel.grid=element_blank(),
                panel.border=element_rect(size=line.width/2),
                axis.ticks=element_line(size=line.width/3),
                axis.ticks.length=unit(0.3, "mm"),
                axis.ticks.margin=unit(0.2, "mm"))

ggsave(file="c:\\temp\\test.png", plot=p, width=40, height=15, units="mm", type ="cairo-png")
Michael Ohlrogge
  • 10,559
  • 5
  • 48
  • 76
Tumbledown
  • 1,887
  • 5
  • 21
  • 33

1 Answers1

23

According to the source code, you also need to set the labels to NULL,

last_plot() + labs(x=NULL, y=NULL)

alternatively, set unit(-0.5, "line") for the bottom and left margins.

Chip Hogg
  • 1,570
  • 13
  • 14
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • 6
    Yes, or ``xlab(NULL)`` to control one label. The more commonly seen ``xlab("")``, like ``axis.title.x=element_blank()``, removes the text but not the space, afaik. And indeed, following up on baptiste's link, line 56 confirms this: ``if (is.null(labels$x)) unit(0, "lines") else unit(0.5, "lines")`` – PatrickT Dec 30 '14 at 21:12
  • this may also help: http://stackoverflow.com/questions/22945651/how-to-remove-space-between-axis-area-plot-in-ggplot2 – Brian D Apr 13 '17 at 16:08