wilkelab / ggtext

Improved text rendering support for ggplot2
https://wilkelab.org/ggtext/
GNU General Public License v2.0
655 stars 37 forks source link

element_textbox_simple ignores hjust #17

Closed eipi10 closed 4 years ago

eipi10 commented 4 years ago

In trying out ggtext I found that element_textbox_simple is ignoring the hjust argument. Here's an example in which I tried to center the title, but it is still left-justified. On the other hand, element_textbox centers the title correctly. Also note, that element_textbox_simple fills the entire title strip, while element_textbox fills only the horizontal extent of the title text. I'm not sure if this is the intended behavior. I'm using version 0.1.0 of ggtext (SHA1: 3b25fcaa).

library(ggplot2)
library(ggtext)

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() + 
  labs(title="this is the title") +
  theme(plot.title=element_textbox_simple(fill="red", hjust=0.5))


ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() + 
  labs(title="this is the title") +
  theme(plot.title=element_textbox(fill="red", hjust=0.5))

Created on 2020-02-06 by the reprex package (v0.3.0)

clauswilke commented 4 years ago

Both behaviors are as designed. Note that hjust governs the alignment of the textbox relative to the enclosing space, and halign governs the horizontal alignment inside the textbox. element_textbox_simple() sets the width to span the entire available horizontal space, therefore hjust doesn't seem to have an effect. But halign works. Similarly, if you explicitly set the width to not span the entire space, you see that hjust works.

library(ggplot2)
library(ggtext)

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() + 
  labs(title="this is the title") +
  theme(plot.title=element_textbox_simple(fill="red", halign=0.5))

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() + 
  labs(title="this is the title") +
  theme(plot.title=element_textbox_simple(fill="red", hjust=0.5, width = NULL))

Created on 2020-02-06 by the reprex package (v0.3.0)

If you just want a label with a colored background, you should probably use element_markdown(). element_textbox_simple() is specifically meant for longer text that requires word wrapping, in which case the default settings make sense.

library(ggplot2)
library(ggtext)

ggplot(mtcars, aes(mpg, hp)) + 
  geom_point() + 
  labs(title="this is the title") +
  theme(plot.title=element_markdown(fill="red", hjust=0.5))

Created on 2020-02-06 by the reprex package (v0.3.0)

eipi10 commented 4 years ago

Got it. Thanks! Sorry to have bothered you.