2

I'm working on creating a forest plot in ggplot and want to display multiple aspects of each study on the y-axis. For a clean look, I want each aspect of each study to line up.

I've used stringr to pad space between each study aspect and then pasted all aspects into a single character string to display as the y-axis label, but I lose this alignment when passing to ggplot. I've tried many different padding strategies (filling on the left/right) and tried playing with hjust, but it seems each aspect is being aligned based on the hjust option rather than the entire string or something

require(stringr)
require(tidyverse)

#Create data frame with studies and aspects of different lengths
df <- data.frame(study = c("study 1", "study 2 long name", "study 3", "study 4 superduper long name"),
                 aspect1 = c("aspect", "longer aspect", "aspect", "long aspect"),
                 aspect2 = c("superduper long aspect", "aspect", "long aspect", "longer aspect"),
                 estimate = c(2,3,4,3),
                 est_lo = c(2,3,4,3) - 1,
                 est_hi = c(2,3,4,3) + 1)

#Generate labels by padding each aspect and then pasting aspects together
df <- df %>% 
  mutate(labels = str_c(str_pad(study, 30, "right"),
                        str_pad(aspect1, 15, "left"),
                        str_pad(aspect2, 25, "left")))

#Plot with ggplot
df %>% 
  ggplot(aes(x = estimate, xmin = est_lo, xmax = est_hi, y = labels)) +
    geom_point() +
    geom_errorbarh(height = 0.2) +
    theme(axis.ticks.y = element_blank(),
          axis.title.y = element_blank(),
          axis.text.y = element_text(hjust = 1))

I expect the ggplot labels to look just like the labels as character strings:

#look at labels as character strings to check alignment
df$labels

[1] "study 1                                aspect   superduper long aspect"
[2] "study 2 long name               longer aspect                   aspect"
[3] "study 3                                aspect              long aspect"
[4] "study 4 superduper long name      long aspect            longer aspect"

But it appears as though ggplot is doing something unexpected with the white space that eliminates the alignment:

from https://imgur.com/a/MxYmKBd

Z.Lin
  • 28,055
  • 6
  • 54
  • 94
cmhoove14
  • 23
  • 4
  • 2
    Looks like you need a monospaced font for this to work as intended. I've answered a similar question before [here](https://stackoverflow.com/a/45809212/8449629). Also check out the [extrafont package](https://cran.r-project.org/web/packages/extrafont/) for font options. – Z.Lin May 02 '19 at 01:50

0 Answers0