Description
An issue to be considered after 2.3.0: I have noticed that descent heights are still not correct. The fault lies in this line:
Line 67 in 4db5122
It looks like a reasonable line, but it turns out that the function descentDetails()
ignores the font settings of the grob it is given:
library(grid)
descentDetails(textGrob("pqgj", gp = gpar(fontsize = 5)))
#> [1] 0.0350748697916667inches
descentDetails(textGrob("pqgj", gp = gpar(fontsize = 10)))
#> [1] 0.0350748697916667inches
descentDetails(textGrob("pqgj", gp = gpar(fontsize = 20)))
#> [1] 0.0350748697916667inches
Instead it takes the font settings from the currently active viewport. The following works correctly:
pushViewport(viewport(gp = gpar(fontsize = 5)))
descentDetails(textGrob("pqgj"))
#> [1] 0.0146145290798611inches
popViewport()
pushViewport(viewport(gp = gpar(fontsize = 10)))
descentDetails(textGrob("pqgj"))
#> [1] 0.0292290581597222inches
popViewport()
pushViewport(viewport(gp = gpar(fontsize = 20)))
descentDetails(textGrob("pqgj"))
#> [1] 0.0584581163194444inches
popViewport()
The result in ggplot is that we're getting the exact same descent height every time, regardless of theme settings:
library(ggplot2)
df <- data.frame(x = 1)
ggplot(df, aes(x, x)) + geom_point() +
ggtitle("gjpjQ") +
theme(plot.title = element_text(size = 10))
ggplot(df, aes(x, x)) + geom_point() +
ggtitle("gjpjQ") +
theme(plot.title = element_text(size = 20))
ggplot(df, aes(x, x)) + geom_point() +
ggtitle("gjpjQ") +
theme(plot.title = element_text(size = 100))
The reason why things seem to work correctly is because the default fontsize is 12, so we're getting a descent height that is approximately right for most typical font sizes.
I have started collecting some grid code for text handling here, in the hopes that some of the code will be useful for future ggplot2 development. Among the code, there is a set of functions to correctly calculate descent heights: https://github.com/clauswilke/gridtext/blob/master/R/grob-descent.R
The approach I'm using works correctly for arbitrary fonts, fontsizes, angles, and vjust
/ hjust
values.
library(grid)
library(gridtext)
library(tibble)
label_data <- tibble(
label = c("Descenders: pgqjy"),
x = unit(c(.2, .5, .8), "npc"),
y = unit(c(.8, .5, .1), "npc"),
box_hjust = c(0, 0.5, 1),
box_vjust = c(0, 0.5, 1),
fontsize = c(20, 17, 14),
fontfamily = c("Comic Sans MS", "Helvetica", "Times New Roman"),
angle = c(0, 35, -35)
)
grid.newpage()
g <- labels_grob(label_data, debug = TRUE)
grid.draw(g)