You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Matplotlib subplots垂直线添加图例及x轴刻度设置

CardioGoodFitness数据集EDA绘图问题修复方案

修复后可直接运行的完整代码

import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.ticker import MultipleLocator

def plott(data, tick_interval=2):
    fig, axes = plt.subplots(3, sharex=True, figsize=(15, 15),gridspec_kw={"height_ratios": (1, 0.2, 0.6)})
    fig.suptitle('Spread of Data for ' + data.name, fontsize=20, fontweight='bold')
    
    sns.histplot(data, kde=True, binwidth=1, ax=axes[0])
    sns.boxplot(x=data, orient='h', ax=axes[1])
    sns.violinplot(x=data, ax=axes[2])
    
    axes[0].set_xlabel('')
    axes[1].set_xlabel('')
    axes[2].set_xlabel('')

    # 仅给第一组参考线加标签,避免图例重复
    axes[0].axvline(data.mean(), color='r', linewidth=2, linestyle='solid', label='均值')
    axes[0].axvline(data.median(), color='r', linewidth=2, linestyle='dashed', label='中位数')
    axes[0].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted', label='众数')
    # 其余子图参考线不需要加标签
    axes[1].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
    axes[1].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
    axes[1].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
    axes[2].axvline(data.mean(), color='r', linewidth=2, linestyle='solid')
    axes[2].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
    axes[2].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
    
    # 共享x轴场景下仅需设置一次刻度规则即可全局生效
    axes[2].xaxis.set_major_locator(MultipleLocator(tick_interval))
    
    axes[0].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
    axes[1].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)
    axes[2].tick_params(axis='both', which='both', labelsize=10, labelbottom=True)

    # 生成图例,可通过loc参数调整位置避免遮挡内容
    axes[0].legend(fontsize=12)
    
    plt.tight_layout()
    plt.show()

# 调用示例:年龄刻度间隔设为2岁
plott(df['Age'], tick_interval=2)
# 需要5岁间隔时传入参数5即可
# plott(df['Age'], tick_interval=5)

关键实现逻辑

  • 参考线图例添加:
    不需要给三个子图的所有垂直线重复设置标签,仅给第一个子图的三条统计参考线传入对应label参数,再调用legend()方法即可自动按线型、颜色匹配生成对应图例,不会出现重复条目。如果图例遮挡绘图内容,可给legend()传入loc参数调整位置,比如loc='upper left'即为左上角位置。
  • x轴刻度间隔调整:
    导入matplotlib.ticker.MultipleLocator类,由于三个子图开启了sharex=True属性,仅需要给任意一个子图的x轴设置主刻度定位器,三个子图的刻度就会同步更新。将想要的刻度间隔数值传入MultipleLocator()即可实现自定义间隔,代码中将间隔设置为函数入参,调用时按需传值即可,无需反复修改函数内部代码。

注:如果数据存在多个众数,当前代码取data.mode()[0]仅展示第一个众数,可根据分析需求调整为展示全部众数。

内容的提问来源于stack exchange,提问作者john wick

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 19:39:16