如何调整Seaborn双Y轴lineplot中标签C的位置避免重叠?
解决Seaborn双Y轴折线图图例/标签重叠问题
当然可以手动调整标签(图例)的位置,以下是几种实用的解决方法:
方法1:合并双轴图例并指定外侧位置
默认情况下,两个轴的图例会挤在同一区域导致重叠,你可以合并两个轴的图例,然后放到图表外侧避免重叠:
sns.lineplot(data=incident_cnt["A"], ax=ax, color="#FF4613", marker='o', label='A') sns.lineplot(data=incident_cnt["B"], ax=ax, color="#80D5FF", marker='o', label='B') ax2 = ax.twinx() sns.lineplot(data=incident_cnt["C"], ax=ax2, color="#00FFAA", marker='o', label='C') # 原有轴标签设置 ax.set_xlabel("Date of index event") ax.set_ylabel("Patients (no)") ax2.set_ylabel("Patients (no) - DIC", color="#00FFAA") ax2.set_ylim(0, ax.get_ylim()[1]/10) # 获取两个轴的图例元素并合并 handles1, labels1 = ax.get_legend_handles_labels() handles2, labels2 = ax2.get_legend_handles_labels() # 将合并后的图例放到图表右上角外侧 ax.legend(handles1 + handles2, labels1 + labels2, bbox_to_anchor=(1.15, 1), loc='upper left') # 隐藏第二个轴的默认图例 ax2.legend_.remove()
注意:要给每个lineplot加上label参数,这样才能正确获取图例文本。
方法2:单独调整两个轴的图例位置
如果不想合并图例,可以分别设置两个轴的图例位置,让它们错开:
# 在绘图后分别设置图例位置 ax.legend(loc='upper left') ax2.legend(loc='upper right')
方法3:精确控制图例的坐标位置
用bbox_to_anchor参数可以更灵活地定位图例,比如把C的图例放到右侧中间位置:
ax2.legend(bbox_to_anchor=(1.05, 0.5), loc='center left')
如果是**Y轴标签(不是图例)**重叠,可以通过调整标签的偏移量解决:
# 调整第二个Y轴标签的距离,避免和左侧标签重叠 ax2.set_ylabel("Patients (no) - DIC", color="#00FFAA", labelpad=25) # 或者手动设置标签的坐标位置 ax2.yaxis.set_label_coords(1.1, 0.5)
内容的提问来源于stack exchange,提问作者Economist_Ayahuasca
相关产品推荐
相关产品推荐

