将其他子图的x轴刻度位置与FacetGrid对象的x轴刻度位置对齐

时间:2020-03-21 15:08:40

标签: python matplotlib seaborn

我想向我的FacetGrid对象添加第二个x轴。我根据this post的建议,通过在图的第一轴下方添加了第二个子图,从而创建了第二个x轴。我的第二个x轴的刻度线应与上面的x轴的刻度线的水平位置匹配。但是,与前面提到的帖子相反,当使用seaborn.catplot时,FacetGrid图案的x轴刻度与x轴的起点和终点不完全匹配。相反,seaborn.catplot“压缩” x轴刻度,以使第一个和最后一个刻度不会与x轴的起点和终点水平对齐。结果,不能简单地使用get_xticksset_xticks设置添加的子图的x轴刻度。

这是一个代码示例:

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)

产生:

enter image description here

1 个答案:

答案 0 :(得分:0)

完全匹配x轴的限制

ax2.set_xlim(g.axes[0,0].get_xlim())