I want to add a second x-axis to my FacetGrid
object. I managed to create a second x-axis by adding a second subplot to my figure that is below the first axis following the suggestions of this post. The ticks of my second x-axis should match with the horizontal locations of the ticks of the upper x-axis. However, in contrast to the post mentioned before, when using seaborn.catplot
, the x-axis ticks of the FacetGrid figure do not exactly match with the beginning and end of the x-axis. Instead, seaborn.catplot
'compresses' the x-axis ticks, so that the first and last tick do not align horizontally with the start and end of the x-axis. As a result, one cannot simply set the x-axis ticks of the added subplot using get_xticks
and set_xticks
.
Here's a code example:
import numpy as np
import pandas as pd
import seaborn as sns
# simulate data
rng = np.random.RandomState(42)
measure_names = np.tile(np.repeat(['Train BAC','Test BAC'],10),4)
model_numbers = np.repeat([0,1,2,3],20)
measure_values = np.concatenate((rng.uniform(low=0.6,high=1,size=40),
rng.uniform(low=0.5,high=0.8,size=40)
))
folds=np.tile([1,2,3,4,5,6,7,8,9,10],8)
plot_df = pd.DataFrame({'model_number':model_numbers,
'measure_name':measure_names,
'measure_value':measure_values,
'outer_fold':folds})
# plot data as pointplot
g = sns.catplot(x='model_number',
y='measure_value',
hue='measure_name',
kind='point',
seed=rng,
data=plot_df)
ax2 = g.axes[0,0].twiny()
# Move twinned axis ticks and label from top to bottom
ax2.xaxis.set_ticks_position("bottom")
ax2.xaxis.set_label_position("bottom")
# Offset the twin axis below the host
ax2.spines["bottom"].set_position(("axes",-0.30))
# set title
ax2.set_xlabel('Title of the second axis')
# get ticks of FacetGrid ax
xtickslocs = g.axes[0,0].get_xticks()
# set ticks of ax2 to first ax
ax2.set_xticks(xtickslocs)
which produces: