secondary x title

This post is on how to articially create a secondary x title.

Miriam Lerma true
2023-11-02

This post is to show how to create a secondary x title in a ggplot

Data

For this example we will create data.
The data includes two species, two subsets and some values.

my_data<-data.frame(my_species=c('a','a','a','a','a','b','b','b','b','b'),
                    my_subset=c('f','m','f','m','f','m','f','m','f','m'),
                    my_values=c(24,15,22,24,31,24,29,26,79,21)
                    )

Then, we will create a artificial grouping.

my_data$my_groups<-paste(my_data$my_species,my_data$my_subset)

Plot

Lets create a plot using ggplot.

Here, I use a geom_violin but the type of the plot is irrelevant for this exercise.
Focus on the x axis.

plot_a<-ggplot(my_data, aes(y=my_values,x=my_groups, color=my_groups, fill=my_groups)) +
  geom_violin(alpha=0.6)+
  geom_point(color='black')+
  theme_bw()
plot_a

Theme

Now lets remove the legend and the title of the x axis.
Lets also replace the text in the x axis.

plot_b<-plot_a+
  theme(legend.position = "none",
        axis.title.x = element_blank())+
  scale_x_discrete(labels=  c("F", "M", "F", "M"))
plot_b

Increase coord

Now, the purpose of the exercise is to add a secondary axis.

To do this, we will expand the space on the y axis.

By doing so we will have more space for the secondary text. Note that it might be difficult to see at first grasp, but there is some empty space.

The arguments to increase the space are:
- coord_cartesian and clip off
- considering the y limit
- change the plot.margin

plot_c<-plot_b+
  coord_cartesian(clip = "off",ylim = c(10, 80))+
  scale_y_continuous(breaks=c(20,40,60,80), 
                     limits=c(-10,80))+
  theme(plot.margin=unit(c(0,0.1,2,0.2),"cm"))
plot_c

Add segments and text

Now in the space created under the y axis, we can add the subtitles using the annotation arguments.

plot_c+
  annotate(geom = "text",x = 1.5,y = -5, label = "Group 1",size = 4)+
  annotate("segment",y = 0, yend = 0,x = 1, xend = 2,colour = "black")+
  
  annotate(geom = "text",x = 3.5,y = -5, label = "Group 2",size = 4)+
  annotate("segment",y = 0, yend = 0,x = 3, xend = 4,colour = "black")

That was it, I hope it helps :)