Home > Mobile >  How to remove the blank region after I move the plot.title to another position in ggplot2?
How to remove the blank region after I move the plot.title to another position in ggplot2?

Time:10-31

I try to move the title to the plot region by using plot.title=element_text(hjust=0.02, vjust=-7). However, it will show a blank region in the top region of plot.

How do I remove the blank region elegantly?

The plot with title and a blank region on the top region of plot is here.

data <- data.frame(name=c('a','b','c','d'),
                   num=c(7, 2, 8, 12))

pp <- ggplot(data=data, aes(x=name, y=num, fill=name)) 
    geom_bar(stat='identity') 
    labs(title='A Title Here') 
    theme(plot.title=element_text(hjust=0.02, vjust=-7))
ggsave(plot=pp, file='pp-a.png', height=6, width=5)

We could use plot.margin to remove the blank:

pp <- ggplot(data=data, aes(x=name, y=num, fill=name)) 
    geom_bar(stat='identity') 
    labs(title='A Title Here') 
    theme(plot.title=element_text(hjust=0.02, vjust=-7),
          plot.margin=unit(c(-5,0.8,0.8,1.0),"mm"))
ggsave(plot=pp, file='pp-b.png', height=6, width=5)

However, if we change the font size of the title, we must reset the plot.margin again. Did anyone have another elegant way?

Thanks for your help.

CodePudding user response:

Instead of moving the plot title around by fiddling with hjust and vjust you could add your title to the plot panel more elegantly and easier by using annotation_custom, e.g. in the code below I place the title in the top left corner and add some padding of 5.5pt. And as your plot now hasn't any "title" doing so will automatically "remove" the blank region which could be seen from the red line I have drawn around the plot.

data <- data.frame(
  name = c("a", "b", "c", "d"),
  num = c(7, 2, 8, 12)
)

library(ggplot2)

ggplot(data = data, aes(x = name, y = num, fill = name))  
  geom_bar(stat = "identity")  
  annotation_custom(grob = grid::textGrob(
    "A Title Here", 
    x = unit(0, "npc")   unit(5.5, "pt"),
    y = unit(1, "npc") - unit(5.5, "pt"),
    hjust = 0, vjust = 1,
    gp = grid::gpar(fontsize = 16)
    ))  
  theme(plot.background = element_rect(color = "red"))

  • Related