Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent title space changing when animating with descender letters

I am trying to animate some monthly data using gganimate. The plots are working great, except that the presence of descenders (letters that go below the baseline, i.e. g, j, p, q, and y) changes the amount of space that the title takes up. This, in turn, moves the baseline of the title just a bit, which detracts from the animation. That is, the title noticably "jumps" up a bit when there is a descender in the title.

An example:

myDF <-
  data.frame(
    Date = seq(as.Date("2015-01-15")
               , as.Date("2015-12-15")
               , "1 month")
    , x = 1:12
    , y = 1:12
  )

myDF$frame <-
  factor(format(myDF$Date, "%Y-%b")
         , levels = paste0("2015-", month.abb))

toAnimate <-
  ggplot(
    myDF
    , aes(x = x
          , y = y
          , frame = frame)
  ) +
  geom_point() +
  theme_gray()

gganimate::gganimate(toAnimate)

enter image description here

Using an older version of gganimate the issue was more obvious(and did not require the inclusion of the year to demonstrate), as it moved the plot instead of the title:

gganimate::gg_animate(toAnimate)

enter image description here

I can "fix" the issue by using all caps (which has no descenders), but I don't particularly like the look of all caps for this (particularly as part of larger titles for the actual use case). I could also prepend the frame title with something that already has a descender e.g. ggtitle("Timeperiod: ") though I'd rather not add irrelevant text just to workaround this issue (adding "Timeperiod: " is what I have gone with for now though).

I've looked through the help on theme in ggplot2, but I am not seeing anything that looks like it would address this issue.

like image 726
Mark Peterson Avatar asked Mar 29 '17 16:03

Mark Peterson


1 Answers

It looks like the title only gets the height of the text, and not the font's height, when reserving space for the title.

So you could instead use geom_text to place a title somewhere in the plot. For example, if I do:

ggplot(myDF, aes(x=x,y=y, label=frame)) +
   geom_point()+theme_gray() + 
   geom_text(x=2.5,y=5,aes(label=frame),adj=0)

(just as a ggplot, not animated yet...) I can see all the 2015's exactly overlapping, and the descenders of the month names are clearly there, and the text baseline is constant.

So if you can put your title in a handy space on the plot, you could use that, and use title_frame=FALSE in your gganimate.

I'd also consider a bug/enhancement report to ggplot2. If you make the title large enough it actually stomps on the plot:

ggplot(myDF, aes(x=x,y=y)) +geom_point()+theme(plot.title=element_text(size=rel(10),debug=TRUE)) + labs(title="y")

enter image description here

like image 141
Spacedman Avatar answered Nov 11 '22 19:11

Spacedman