0
df <- data.frame (yaxis = rnorm(120,5,1),
                  xaxis = rep(c("A - S. longishname","B - S. longishname","C - S. longishname","A - S. short","B - S. short", "B - S. med"), 20))
                  
ggplot(df, aes(x = xaxis, y  = yaxis)) + geom_point()+ theme_classic() + scale_x_discrete(labels=expression(italic("A - "),italic("B - "),italic("C - "),italic("A - "),italic("B - "), italic("B - ")))  #+ scale_x_discrete(labels=expression(italic("S. longishname"),italic("S. short"),italic("S. med"))) 

Code output: enter image description here

What I want: Primarily: The secondary label i.e. the phrase that is common for every few species If possible the brackets that look lik the follows (axis label with sufficient vertical space is first prioirty)

enter image description here

Share
  • 395
  • 7
  • 19

1 Answers1

0

You can use facet_wrap to add panels to your plot which can sort of act as secondary labels. Try adding a column to your data with desired secondary labels. Then use face_wrap to add them in your plot.

library(ggplot2)
library(dplyr)

# set seed, since using rnorm
set.seed(123)

df <- data.frame (yaxis = rnorm(120,5,1),
                  xaxis = rep(c("A - S. longishname","B - S. longishname","C - S. longishname","A - S. short","B - S. short", "B - S. med"), 20))

# create sublabels and remove unnecessary substr
df <- df |> 
  mutate(
    sublabels = case_when(grepl("longishname", xaxis) ~ "S. longishname",
                          grepl("short", xaxis) ~ "S. short",
                          grepl("med", xaxis) ~ "S. med"
    ),
    # reorder sublabels
    sublabels = factor(x = sublabels, levels = c("S. longishname", "S. short", "S. med")),
    # remove S. short, S. med, S. longishname from xaxis
    xaxis_processed = gsub("S. (short|med|longishname)", "", xaxis)
  )

# plot using facet_wrap
df |> 
  ggplot(aes(x = xaxis_processed, y = yaxis)) + 
  geom_point()+ 
  theme_classic() +
  facet_wrap(~sublabels, strip.position = "bottom", scales = "free_x")

enter image description here

nightstand
  • 329
  • 2
  • 11