remove space on sides of ggplot, even when margin is 0

1k Views Asked by At

I'm having a ggplot spacing problem.. probably just not knowing the exact theme element I'm looking for. when I make a ggplot and remove all axis markings, then make all margins 0, there is still a little bit of space between the panel and the outside of the plot that is making my plot asymmetrical. How do I remove this?

data.frame(x=1,y=1) %>%
  
  ggplot(aes(x=x,y=y))+
  geom_point()+
  ggthemes::theme_few() +
  labs(x=NULL,y=NULL)+
  
  theme(axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.line = element_blank(),
        panel.background = element_rect(fill="powderblue",color="black",size=2),
        plot.margin = margin(0,0,0,0,"pt"))

see the tiny bit of white space on the left and the bottom. Also, if we move the (nonexistent, I thought) x-scale to the top by adding + scale_x_continuous(position="top"), the space moves there. So there must be some remnants of scale markings that are creating this space by default. Is there a way to remove it?

Thanks!

2

There are 2 best solutions below

0
BHuber On

I output your base example to file and don't believe that there is any additional border. I think what you might be seeing is a part of the RStudio GUI.

library(ggplot2)
library(ggthemes)
library(magrittr)

png()
data.frame(x=1,y=1) %>%
  
  ggplot(aes(x=x,y=y))+
  geom_point()+
  ggthemes::theme_few() +
  labs(x=NULL,y=NULL)+
  
  theme(axis.title = element_blank(),
        axis.text = element_blank(),
        axis.ticks = element_blank(),
        axis.line = element_blank(),
        panel.background = element_rect(fill="powderblue",color="black",size=2),
        plot.margin = margin(0,0,0,0,"pt"))

dev.off()
0
Jake L On

figured it out- even if you set axis.ticks to element_blank(), you still need to add axis.ticks.length = unit(0, "pt"), to remove the space that they would occupy, then that gets rid of the extra space around the plot.