繁体   English   中英

垂直线的 subplots() 中的图例 Matplotlib.pyplot Python

[英]Legend in subplots() for vertical lines Matplotlib.pyplot Python

我正在尝试使用 Kaggle 数据集链接进行 EDA

我制作了一个带有 3 个子图的图,并根据均值、中位数和众数绘制了 3 条垂直线。 有没有办法在图例中显示这 3 行?

这是我的代码

def plott(data):
    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')
    axes[0].axvline(data.median(), color='r', linewidth=2, linestyle='dashed')
    axes[0].axvline(data.mode()[0], color='r', linewidth=2, linestyle='dotted')
    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')
    
    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)
    
    


plott(df['Age'])

这是结果图

在此处输入图像描述 有没有办法根据这样的3条垂直线在此处添加图例,每种线型都表示值?

在此处输入图像描述

另外,如何在所有三个图形的 x 轴上添加更多值? 比如让它间隔5或2年?

谢谢

给 axvlines 一个“标签”值,然后在绘制后调用plt.legend

例子:

import matplotlib.pyplot as plt

plt.plot([1,2,3],[1,2,3],label="Test")
plt.axvline(x=0.22058956, label="Test2", color="red")
plt.legend()

输出: 在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM