【问题标题】:Adding a legend to a boxplot in matplotlib/seaborn在 matplotlib/seaborn 中向箱线图添加图例
【发布时间】:2020-09-16 01:54:00
【问题描述】:

我是 Python 新手。

我使用以下代码在 matplotlib/seaborn 中生成了一个箱线图(带有 swarmplot 覆盖)。我现在想添加一个遵循每个框的配色方案的图例。我在网上找到的许多解决方案似乎不适用于这种特定类型的图表(例如,仅适用于 grouped boxplots)。

当我尝试实现here 建议的代码时,我收到了错误消息。

非常感谢所有输入!

# Import libraries and modules

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

# Set seaborn style.

sns.set(style="whitegrid", palette="colorblind")

# Load summary tidy data.

tidy = pd.read_csv('tidy.csv')

# Define plots for tidy data

fig, ax = plt.subplots(figsize=(10,6))
ax = sns.boxplot(x='header1', y='header2', data=tidy, order=["header1", "header2"])
ax = sns.swarmplot(x="header1", y="header2", data=tidy, color=".25", order=["header1", "header2"])
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'header1'
labels[1] = 'header2'
ax.set_xticklabels(labels)
ax.legend(loc='best')

我正在使用的数据示例。

Object,Metric,Length
MT1,B2A1,3.57675
MT1,B2A2,2.9474600000000004
MT1,B2A3,2.247772857142857
MT1,B2A4,3.754455
MT1,B2A5,2.716282
MT1,B2A6,2.91325
MT10,B2A1,3.34361
MT10,B2A2,2.889958333333333
MT10,B2A3,2.22087
MT10,B2A4,2.87669
MT10,B2A5,1.6745005555555557
MT12,B2A1,3.3938900000000003
MT12,B2A2,2.00601
MT12,B2A3,2.1720200000000003
MT12,B2A4,2.452923333333333

【问题讨论】:

  • 您在主代码中在哪里调用ax.legend()
  • 感谢您的关注!我错过了将它添加到示例中。我在设置 xticklabels 后调用了 legend。
  • 那么header1header2 是什么?公制和长度?
  • 是的,完全正确!如果我在代码中使所有名称中立,我认为会更容易概述。这是一个错误吗?

标签: python matplotlib seaborn legend boxplot


【解决方案1】:

no handles with labels found to put in the legend 错误是由于调用ax.legend() 而您的两位艺术家(箱线图和群图)没有标签。

sns.boxplot 基于 scatter 上的 matplotlib 的 boxplotsns.swarmplot,因此您只需分别给它们一个 labelslabel 参数。

ax = sns.boxplot(..., labels=["Metric", "Length"])
ax = sns.swarmplot(..., label="something goes here")

或者,根据this,您可以保持 seaborn 部分不变并摆弄:

handles, _ = ax.get_legend_handles_labels()          # Get the artists.
ax.legend(handles, ["label1", "label2"], loc="best") # Associate manually the artists to a label.

【讨论】:

    猜你喜欢
    • 2020-08-08
    • 1970-01-01
    • 2018-04-08
    • 2015-06-29
    • 2014-03-22
    • 2019-12-07
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多