簡體   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