复现Seaborn热力图共享Y轴时遇GrouperView无join属性错误
解决
AttributeError: 'GrouperView' object has no attribute 'join'问题 问题场景
尝试复现旧版Stack Overflow答案时,运行代码出现以下错误:
AttributeError: 'GrouperView' object has no attribute 'join'
完整报错栈:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) Cell In[283], line 7 4 flights = flights.pivot("month", "year", "passengers") 5 f,(ax1,ax2,ax3, axcb) = plt.subplots(1,4, 6 gridspec_kw={'width_ratios':[1,1,1,0.08]}) ----> 7 ax1.get_shared_y_axes().join(ax2,ax3) 8 g1 = sns.heatmap(flights,cmap="YlGnBu",cbar=False,ax=ax1) 9 g1.set_ylabel('') AttributeError: 'GrouperView' object has no attribute 'join'
当前使用的库版本:
print(sns.__version__) # 0.13.0 import matplotlib print('matplotlib: {}'.format(matplotlib.__version__)) # matplotlib: 3.8.1
原因分析
matplotlib 3.8.0版本对轴共享API做了更新:get_shared_y_axes()不再返回旧版的SharedAxes对象,而是返回GrouperView,而GrouperView没有join方法。
解决方案
有两种可行的修复方式:
方式1:替换join为add方法
将原来的一行代码拆分为两次调用add方法,把需要共享轴的子图加入目标轴的共享组:
# 替换 ax1.get_shared_y_axes().join(ax2,ax3) shared_y_group = ax1.get_shared_y_axes() shared_y_group.add(ax2) shared_y_group.add(ax3)
方式2:创建子图时直接指定共享轴
在调用plt.subplots时通过sharey参数直接设置共享y轴,更简洁:
f,(ax1,ax2,ax3, axcb) = plt.subplots(1,4, gridspec_kw={'width_ratios':[1,1,1,0.08]}, sharey='row') # 此时无需再手动调用轴共享相关方法
内容的提问来源于stack exchange,提问作者Mario
相关产品推荐
相关产品推荐

