【问题标题】:Creating a key for box plot mean and median lines in Matplotlib在 Matplotlib 中为箱线图均值线和中线创建键
【发布时间】:2020-04-14 04:38:44
【问题描述】:

我有以下代码,它创建了一个 APOE4 基因拷贝和记忆分数的箱线图(因此是变量名)

clean_merged.boxplot('composite scores', by='APOE4', widths = 0.8, showmeans = True, meanline = True)
plt.title('Mean Composite Memory Score by APOE4 Copies')
plt.xlabel('Number of APOE4 Copies')
plt.ylabel('Composite Memory Score')
plt.rcParams['figure.figsize'] = (10,10)

生成此输出:

我想为平均值(绿色虚线)和中线(实心填充)添加一个图例,并且根据之前提出的问题正在努力做到这一点,因为我创建图表的方式与通常建议的方法完全不同。

我是 python 新手,因此感谢任何帮助 :) 谢谢!!!

【问题讨论】:

    标签: python matplotlib legend boxplot legend-properties


    【解决方案1】:

    您可以在绘图中添加“空”线,为它们分配适当的样式、颜色和标签。这些将由plt.legend() 接收。由于我没有你的数据,我以 seaborn 的 Titanic 数据集为例:

    import pandas as pd
    import matplotlib.pyplot as plt
    import seaborn as sns
    sns.set()
    
    titanic = sns.load_dataset('titanic')
    titanic.boxplot('age', by='sex', widths=0.8, showmeans=True, meanline=True)
    
    plt.plot([], [], '-', linewidth=1, color='Crimson', label='mean')
    plt.plot([], [], '-', linewidth=1, color='gray', label='median')
    
    plt.legend()
    

    【讨论】:

    • 这正是我想要的!我发现你可以使用'--' 在图例中画一条虚线,效果很好。非常感谢
    • 很高兴我能帮上忙。
    猜你喜欢
    • 2017-10-22
    • 2019-03-19
    • 2019-12-31
    • 1970-01-01
    • 2021-08-22
    • 1970-01-01
    • 2013-07-17
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多