How to get rid of whitespace in a ggplot2 plot?

2019-04-26 15:08发布

问题:

I'm preparing a figure for a publication. I'm omitting the x label by setting xlab(""), however ggplot2 produces a whitespace instead of completely removing the label. How can I get rid of the whitespace (marked by red rectangle in the plot below)?

The full code:

ggplot(data, aes(x=Celltype, y=Mean, fill=factor(Dose), label=p.stars)) +
  geom_bar(stat = "identity", position = position_dodge(width=0.9), aes(group=Dose)) +
  geom_errorbar(aes(ymin = Mean - SEM, ymax = Mean + SEM), stat = "identity", position = position_dodge(width=0.9), width=0.25) +
  geom_text(aes(y = Mean + SEM), size = 5, position = position_dodge(width=0.9), hjust = .5, vjust = -1) +
  xlab("") +
  ylab("Concentration") +
  scale_fill_grey(name = "Dose") +
  theme_bw()

回答1:

Use theme() to remove space allocated for the x axis title. When you set xlab("") there is still space made for this title.

+ theme(axis.title.x=element_blank())


回答2:

Have you tried plot.margin?

library(grid)
ggplot(data, aes(x=Celltype, y=Mean, fill=factor(Dose), label=p.stars)) +
  geom_bar(stat = "identity", position = position_dodge(width=0.9), aes(group=Dose)) +
  geom_errorbar(aes(ymin = Mean - SEM, ymax = Mean + SEM), stat = "identity", position = position_dodge(width=0.9), width=0.25) +
  geom_text(aes(y = Mean + SEM), size = 5, position = position_dodge(width=0.9), hjust = .5, vjust = -1) +
  xlab("") +
  ylab("Concentration") +
  scale_fill_grey(name = "Dose") +
  theme_bw() +
  theme(plot.margin = unit(c(1,1,0,1), "cm")) # ("left", "right", "bottom", "top")


回答3:

Try this function:

savepdf <- function(file, width=16, height=10) {
            fname <- paste("figures/",file,".pdf",sep="") 
            pdf(fname, width=width/2.54, height=height/2.54, 
                 pointsize=10)
            par(mgp=c(2.2,0.45,0), tcl=-0.4, mar=c(3.3,3.6,1.1,1.1))
}

You can also crop the white space in the resulting pdf file once created. In Unix, the system command is:

pdfcrop filename.pdf filename.pdf

pdfcrop does work on Mac provided the standard LaTeX distribution (Mactex or texlive) is installed. Of course, this command can be executed in R as follows:

system(paste("pdfcrop", filename, filename))