ggplot2 axis and legend text misalignment

I was trying to find a way to align axis text labels with superscripts or subscripts. I learnt that the default alignment was to the top but the misalignment occurred if the text has some superscripts or subscripts which add to the overall height of the text.

library(tidyverse)

p <- ggplot(ToothGrowth, aes(supp, len, color = supp)) + 
  geom_point() +
  scale_x_discrete(label = c(bquote(T7["-/-"]), bquote(T7^"-/-"))) +
  theme(
  axis.text.x = element_text(vjust = 0.5, debug = TRUE)
)

p

Created on 2019-03-30 by the reprex package (v0.2.1)

I am thinking if there is an workaround that we can just align all texts without the superscripts and subscripts to the center themselves (for the legend, they can be aligned to the key center as well). For example, we only care about the part of T7 during alignment even though the expression is bquote(T7["-/-"] and it will look like (sorry, the image is in the comment)

I know it is quite hard but was still wondering if there is any possibility that ggplot2 can achieve this.

Here is the image in the topic.

There may be a less hacky way, but one option is to create a phantom superscript in the first label and a phantom subscript in the second. The phantom function creates a gap where a given string would be, but doesn't draw the string. As you can see in the image, "T7" is now in the same vertical position in each label. The theme statement is not necessary for vertical alignment.

ggplot(ToothGrowth, aes(supp, len, color = supp)) + 
  geom_point() +
  scale_x_discrete(label = c(bquote(T7["-/-"]^phantom("/")), 
                             bquote(T7[phantom("/")]^"-/-"))) +
  theme(axis.text.x = element_text(vjust = 0.5, debug = TRUE))

Rplot11

3 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.